Search code examples
reactjsstatereact-state-managementuse-context

how to add new property to react useContext state


I have a little problem, I'm learning reactjs. I'm trying to add a property to an object in the cart array called quantity; when similar item with same id is equal to the iterator, to add a property quantity and increase it's value. I'm learning both react and javascript I'm coming from a python background so... Here is my code.

 const addToCart = (item) => {
    if (cart.length){
        for (let iter of cart){
            if (iter.id===item.id){
                item.quantity += 1 // this is 'NaN' if quantity wasn't declared.
                setCart([...cart, item])
            }else{
                setCart([...cart, item])
            }
        }
    }
}

this code does... Nothing!


Solution

  • If I understand you correctly you want to increment the quantity if the item exist in the cart, otherwise add it to the cart ? if so try the following:

    const [cart, setCart] = useState([]);
    
    ...
    
    const addToCart = (item) => {
        // declare the quantity property if it doesn't exist
        item.quantity = item.quantity || 1;
        // get the index from the cart
        const i = cart.findIndex(obj => obj.id === item.id);
        // if the item exists increment the quantity
        if(i > -1) {
          const newCart = [...cart];
          newCart[i].quantity = item.quantity + 1; 
          setCart(newCart)
        } else {
          // the item doesn't exist so add it to the cart
          setCart([...cart, item]);
        }
     }