Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

495
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!