0

i want to add a new object to an array of objects when id does not match in react recoil

const [cart, setCart] = useRecoilState(cartItems)

object {id:1, quantity:1, productName:'apple'}

const addToCart =(object) => {
        
        if(cart.length==0){
            setCart([object])
        }
        else{
            let data = cart.map(items=>
                {
                    if(items.id == object.id )
                    {
                        return {...items, quantity:items.quantity + cartData.quantity}
                    }else
                    {
                        
                    }
                })                
            setCart(data)
        }
}

ASIF KAIF
  • 317
  • 1
  • 4
  • 17

1 Answers1

0

You could use

findIndex()

to find an element that satisfies your condition. It returns -1 if it can't find anything.

const index = cart.findIndex(item => item.index == object.id);
if (index == -1) setCart([...cart, object])
else ...
Syph
  • 1,239
  • 1
  • 9
  • 16