Home > Net >  Youtube playlist thumbnail image not working in Next Js
Youtube playlist thumbnail image not working in Next Js

Time:08-09

In my next js app I'm fetching YouTube playlist and assigning them dynamic card. but when I use map the url doesn't work but in plain omg tag it works fine.

the code is as follows. index.js

function Home({result}) {
   return (
     <...
      <ShowsView result={result}/>
     .../> 
)
} export default Home;

export async function getStaticProps(){
  const MY_PLAYLIST = process.env.YOUTUBE_PLAYLIST_ID;
  const API_KEY = process.env.YOUTUBE_API_KEY;
  const REQUEST_URL = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${MY_PLAYLIST}&key=${API_KEY}`;

  const response = await fetch(REQUEST_URL);
  const result = await response.json();

  return{
    props:{result: result},
    revalidate: 3600,
  }
}

in my index file executing result.items[0].snippet.thumbnails.maxres.url will return a url for the image. the issue is when I map it through the url doesn't work.

{result.items.map((res, idx)=>{
          //console.log(res.snippet.thumbnails.maxres);
          //console.log(res);
          //console.log(result);
          return (
            //<ShowCard result={result.items[idx].snippet.thumbnails.maxres.url} key={idx}/>
         <ShowCard result={res.snippet.thumbnails.maxres.url} key={idx}/>
          );
        })}

using like this it return every data until I get to the thumbnails. res.snippet.thumbnails.default this works. but res.snippet.thumbnails.default.url throws an error.

TypeError: Cannot read properties of undefined (reading 'url')

This error happened while generating the page. Any console logs will be displayed in the terminal window

the log points after default. what is the mistake here?

CodePudding user response:

Perhaps res is also being accessed during init of the app, which is an empty object.

try doing this:

res.snippet.thumbnails.default?.url
  • Related