I'm trying to set the a state with an array of objects but I'm getting the above error and I do not know how to resolve it.
My code:
const [itemsInCart, setItemsInCart] = useState([]);
useEffect(() => {
const fetchData = async () => {
await fetch("https://fakestoreapi.com/products?limit=16")
.then((res) => res.json())
.then((data) => {
const initialItemCount = data.map((item) => {
return {
name: item.title,
qty: 0,
};
});
setItemsInCart(initialItemCount);
});
};
fetchData();
}, []);
I tried console.log(Array.isArray(initialItemCount))
to check if it is an array and it returned true. So why is it saying to use an array? Thank you
You can use a breakpoint to see the final value of itemsInCart
, to check if this array contains the list of React child component.
From your code, I guess the array only contains the object of {name and qty}, which can not be rendered directly.
You may try parsing these objects to a component to render UI.
Hope this help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.