Search code examples
javascriptreactjsuse-state

In reactusestate setcart function is not working


const [cart, setCart] = useState([]);

const addToCart = (item) => {
  // cart.push(item);
  setCart(...cart, item);
  console.log(cart);
};

when I try to update cart with cart.push() , it is updating cart but when i try to update cart with setCart then its showing this error

=> TypeError: object is not iterable (cannot read property Symbol(Symbol.iterator))

Solution

  • The best way to do this without bugs would be to use a function inside setCart that takes the previous state and updates it. It would look like this:

    const [cart, setCart] = useState([]);
    
    const addToCart = (item) => {
        setCart(prevState => {
          return [...prevState, item];
        });
    }
    

    An alternative shorter syntax (does the same thing) using would be:

    const [cart, setCart] = useState([]);
    
    const addToCart = item => setCart(prevState => ([...prevState, item]));