user14866403
user14866403

Reputation:

How to remove element from array object use in redux reduce state?

In my react app I create a store and reducer using redux.

And I have one state name as "cart" which is an object array.

And I want to remove and an element which I pass the id as a payload in reducer case only.

How can I remove an element from this state which is id equal to payload ID?

This is cart state structure

enter image description here

const reducer = (state = initialState, action) => {
       case actionTypes.QUANTITY_COUNT:
            const newCart = {...state.cart};
            if (newCart[action.id].quantity === 1){
                 //here i want to remove element from cart/newCart of Id as action.id
              }
}

Upvotes: 0

Views: 1274

Answers (2)

amirhe
amirhe

Reputation: 2341

Actually delete keyword is not designed for doing this task. Also, the idea behind the reducer is to make a new state so copying state and then deleting an element is something you must try to do in proxied packages such as immer not js itself.

here are some tips for working with objects as there are many number of questions about state change with objects.

const state = { isActive: true, props: { userId: {} } }
Object.keys(state) // ['isActive', 'props']
Object.entries(state) // [['isActive', true], ['props', { userId: {} }]]
Object.keys(state).map((key, index) => state[key]) // // [true, { userId: {} }]

as I mentioned deleting doesn't play a good role here instead the better way to change sub-part object is using immer, or filter


const newCart = Object.keys(state.cart).filter(() => state.cart[action.id].quantity !== 1)

Upvotes: 1

Alamin
Alamin

Reputation: 2165

You can try this logic, this is works for my case:

      const reducer = (state = initialState, action) => {
       case actionTypes.QUANTITY_COUNT:
            const newCart = {...state.cart};
            if (newCart[action.id].quantity === 1){
                  delete newCart[action.id]
                 
              }
}

Upvotes: 0

Related Questions