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} />
));
}
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: