0

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))

enter image description here

UPDATE

Why doesn't this work here?

const [shoppingBag, setShoppingBag] = React.useState([]);


 const shopping = (item) => {
  setShoppingBag(...shoppingBag, item);
};
Captai-N
  • 1,124
  • 3
  • 15
  • 26
  • I think this link will answer your question as well as you want https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate – Omar Zaoujal Jun 09 '22 at 09:08

2 Answers2

0
setShoppingBag([...shoppingBag, ...shoppingArray]);
0

You are missing array [] in the function call. setShoppingBag(...shoppingBag, shoppingArray); should be setShoppingBag([...shoppingBag, shoppingArray]);

Tea_Lover_418
  • 308
  • 2
  • 10