Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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

{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>
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

add a ? to your tags like this

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

or change your conditional rendering to :

{movies.length &&

about 4 years ago · Juan Pablo Isaza Denunciar

0

It can be tough to remember what values are coerced to true or false by JavaScript. In this case, an empty array ([]) is actually a "truthy" value (see MDN for examples), so your FilmCard elements will be rendered unwantedly.

Either change your conditional to account for this:

{movies.length &&

Or initialize movies as a "falsy" value:

const [movies, setMovies] = useState(null)
about 4 years ago · Juan Pablo Isaza Denunciar

0

I do fetch data like this:

useEffect(()=>{
  (async () => {
    const request = await axios.get(fetchUrl);
     setMovies(request.data.results); 
  })()
},[fetchUrl])

And you should check if movies is not null. in the return add

{movies.length > 0 && // What you want to do with movies.}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda