Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Uncaught TypeError: Cannot read properties of undefined (reading 'poster_path')

I have this async function that is fetching data from the API but when I use the data it gets a type error of undefined with movies array. But then I use "&&" to tell it that if it’s empty then don’t execute the block but it still gives the error. I have done it by the ternary operator too but still the same.

Here is the use effect hook which is fetching data from API

const [movies, setMovies] = useState([])
useEffect(() => {

   async function fetchData() {

     const request = await axios.get(fetchUrl);
     setMovies(request.data.results);
     console.log(movies);
     return request;
   }

   fetchData();
}, [fetchUrl]);

And here is the code for that element

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{movies &&
    <div id="film-row">
      <FilmCard img={`${base_url}${movies[0].poster_path}`} />
      <FilmCard img={`${base_url}${movies[1].poster_path}`} />
      <FilmCard img={`${base_url}${movies[2].poster_path}`} />
      <FilmCard img={`${base_url}${movies[3].poster_path}`} />
      <FilmCard img={`${base_url}${movies[4].poster_path}`} />
      <FilmCard img={`${base_url}${movies[5].poster_path}`} />
    </div>
}

>Solution :

add a ? to your tags like this

  <FilmCard img={`${base_url}${movies?.[0]?.poster_path}`} />

or
change your conditional rendering to :

{movies.length &&

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading