I am getting an error in the console as follows:
Cannot read properties of undefined (reading 'map')
I've searched online extensively for the past few hours and all the solutions state that the async call isn't defined and that's why no value is passed to the map. Thing is, it is defined and called with an empty object to force the await. Please could somebody let me know what I'm missing in the below code?
const [product, setProduct] = useState({});
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("products/find/" id);
setProduct(res.data);
} catch (err) {}
};
getProduct();
}, [id]);
This gets a 'Product' object, which contains an array field called colour. I use this to display several options on the page.
{product.colour.map((c) => (
<FilterColor colour={c} key={c} />
))}
When I change the use effect code to console log the res.data.colour, I get the colour values. I don't understand why this map throws this undefined error, when the product is defined as a result of the setProduct call.
I hope someone can help :)
Edit: Other bits of code that will help understanding of the above:
export const publicRequest = axios.create({ baseURL: BASE_URL,});
and this is how I get console.log to display the colours, by changing the useeffect section:
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("products/find/" id);
setProduct(res.data);
console.log(res.data.colour); //this displays an array of colours in the console
} catch (err) {}
};
getProduct();
}, [id]);
and without using the map() function, I can display data like this: <Title>{product.title}</Title>
CodePudding user response:
This happens because, when first the page is rendered which is before the api fetch has actually completed, your product value is {}
, so when you do product.colour.map
since it doesn't have any colour
property you will get Cannot read properties of undefined
error.
So what you need to do is either
const [product, setProduct] = useState({colour: []});
or in your map do
{product?.colour.map((c) => (
<FilterColor colour={c} key={c} />
))}