Search code examples
javascriptreactjsreact-props

How map date with different API Javascript


How can I use date with different API (e.g., YouTube, Vimeo)? In state I have a table with objects, objects are different. I map this table to Component.

{items.map((item) => (<Item key={uuidv4()} product={item}></Item>))}

I don't have an idea how can I use here props to have title, img and likeCount when path to the goal is different.

Path to YouTube title:

const title = props.item.snippet.localized.title;

Path to Vimeo title:

const title = props.item.name;

I tried this but it doesn't work.

export default function Video(props) {
    const title = props.item.snippet.localized.title || props.item.name;
    return (
        <div>{title}</div>
    );
}

Solution

  • You can use the ?? to use this:

    {items.map((item) => (<Item key={uuidv4()} product={item.name ?? item.snippet.localized.title}></Item>))}
    

    Otherwise a more complex arrow function is fine too:

    {items.map((item) => {
        const title = ...;
        return <Item key={uuidv4()} product={title/>;
    })}
    

    If your problem is that props.item.snippet.localized.title errors due to e.g. .snippet being undefined, try optional chaining:

    const title = props.item.snippet?.localized?.title ?? props.item.name;