Skip to content
Advertisement

How can I get an image from Youtube search App in react?

async function searchYouTube(query ) {
    query = encodeURIComponent(query);
    const response = await fetch("https://youtube-search-results.p.rapidapi.com/youtube-search/?q=" + query, {
        "method": "GET",
        maxResult: 2,
        "headers": {
            "x-rapidapi-host": "youtube-search-results.p.rapidapi.com",
            'X-RapidAPI-Key': '39c26367dbmsh777490f3d0910cfp1baab3jsn22fdcdd9ff8c'

        }
    });
    const body = await response.json();
    console.log("body",body);
    return body.items.filter(item => item.type === 'video');
}

in my code you can see , i can get any info expect image,can you explain me where is the wrong code

How do I display the video Image of the search results using YouTube Search Results API? also in photo below you can see i get image info ,, but in code i cant show it

enter image description here

function Search() {
    const [query, setQuery] = useState('bts');
    const [list, setList] = useState(null);
    const search = (event) => {
        event.preventDefault();
        searchYouTube(query).then(setList);
    };
              
    return (
        <div className="app">
            <form onSubmit={search}>
                <input autoFocus value={query} onChange={e => setQuery(e.target.value)} />
                <button>Search YouTube</button>
            </form>
            {list &&
            (list.length === 0 ? <p>No results</p>
                    : (
                        <ul className="items">
                            {list.map(item => (
                                <li className="item" key={item.id}>
                                    <div>
                                        <b><a href={item.link}>{item.title}</a></b>
                                        <p>{item.description}</p>
                                    </div>
                                    <ul className="meta">
                                        <li>By: <a href={item.author.ref}> 
                                         {item.author.name}</a></li>
                                        <li>Duration: {item.duration}</li>
                                    </ul>
                                    <img alt={item.link} src={item.thumbnails} />
                                    {console.log("image",item.thumbnails)}
                                </li>
                            ))}
                        </ul>
                    )
            )
            }
        </div>
    );
}

export default Search;

Advertisement

Answer

As I can see in the console, item.thumbnails returns an array of objects. inside that object you might have some property like url or something else to access the actual thumbnail url. So you may need to access that property:

<img alt={item.link} src={item.thumbnails[0].url} />
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement