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

506
Vistas
data property in useQuery() hook returns Cannot read properties of undefined

This is an extremely perplexing issue. The code below gives this error:

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

When console.log() is used to look at res.data it is fine, it has data. res.data.products is undefined, therefore blowing up the .map(). It just doesn't make sense why this doesn't work. Starting to think there is a bug in the react-query library

export default function ProductList() {
  const { data: products, isLoading } = useQuery('Products', () => 
    axios('/api/products').then((res) => res.data.products)
  );

  if (isLoading) return <LoadingSpinner />

  return products.map((product) => (
    <ProductItem key={product.id} product={product} /> 
  ));
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Data returned from useQuery is of type undefined | T. Meaning it can either be undefined or the shape you expect it to be in. This is because, when you first fetch your data you don't have it in your cache, so you must acquire it, typically through an HTTP request. Because this data has the potential to be undefined, you must protect against the undefined case.

return (products?.map(..

If you update your code to the above what it will first do is check and see if products are defined. If it hasn't been defined it will then provide an empty array to the map function. Since there's nothing to map over the return statement is an empty array.

Additionally, if you put your console log statement immediately after useQuery call you should notice that it first uses undefined, only later after the request has been resolved will data begin to flow.

That said, there is a case where isLoading is false, but the data is 'undefined` because it was never able to resolve itself.

Think about it this way:

  • what should we display see while loading
  • what should we display when the data is ready
  • what should we display when we are no longer loading and the data failed to be returned
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