0

I had this problem where i needed to make it so that an item can't be added twice in my shopping cart, then I searched this platform to see if there were any answers. I found out the question was asked Check if item already exists in cart when adding REACT but there were no sufficient contributions on it. Eventually i got the problem solved on my own but i wasn't allowed to contribute in the comments(I'm new here). So i decided to leave this here incase some one needs same.

I use context API and useReducer. Here is was my code

    switch (action.type) {
        case ADD_T0_CART:
        
        return {
                
                ...state, basket: [...state.basket, action.payload]
            }
            ```

After some hours of headache i eventually fixed it using a simple JS find() function.

  ```  export const commerceReducer = (state,action) => {
        switch (action.type) {
            case ADD_T0_CART:
                const itemExists = state.basket.find(
                    (item) => item.id === action.payload.id 
                )
                console.log(itemExists)
              
                if (!itemExists) return {
                    
                    ...state, basket: [...state.basket, action.payload]
                }
            ```
Hope someone finds this helpful.
  • I am facing kind of a similar issue here. Have a look. https://stackoverflow.com/questions/74057542/dynamically-change-the-button-from-active-to-inactive-after-removing-or-adding-i – Jesee Kiigu Oct 15 '22 at 08:43

1 Answers1

0

I usually use the filter method on the cart object in the state. The filter happens before pushing the payload to the cart state.

Something like this will filter out the duplicates and save the most recent one.

const item = {
 id: '1',
 first_name: 'John',
 last_name: 'Doe'
}

const filtered = state.cart.filter((element, index, array) => {
  if (String(element.id) === String(action.payload.item?.id)) {
     const indexof = state.cart.indexOf(element);
     state.cart.splice(indexof, 1);
    }
});

state.cart = [...state.cart, item];

I hope this helps.

kodaq
  • 39
  • 8