everyone. I'm trying to store an object into a hook array after the user clicks a button for a product. However, I keep getting an: object is not iterable error.
The Main Part:
let shoppingArray = [];
const shopping = (item) => {
shoppingArray.push(item);
console.log(shoppingArray);
setShoppingBag(...shoppingBag, shoppingArray);
};
...
<ShoppingCartOutlinedIcon className="icons" onClick={() => shopping(item)}></ShoppingCartOutlinedIcon>
Error code:
Uncaught TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))
UPDATE
Why doesn't this work here?
const [shoppingBag, setShoppingBag] = React.useState([]);
const shopping = (item) => {
setShoppingBag(...shoppingBag, item);
};
CodePudding user response:
setShoppingBag([...shoppingBag, ...shoppingArray]);
CodePudding user response:
You are missing array [] in the function call. setShoppingBag(...shoppingBag, shoppingArray);
should be setShoppingBag([...shoppingBag, shoppingArray]);
CodePudding user response:
You can try this
const shopping = (item) => {
const shoppingArray = [...shoppingBag]
shoppingArray.push(item);
setShoppingBag(shoppingArray);
};