Sunil tc
Sunil tc

Reputation: 2602

How to add & remove item from reducer state in react

this is my reducer. I want to add new data to my data without duplication. But while adding new data, i'm getting duplication of data. and also I want to remove data based on ID.

Can anyone please help me.

How to update the data ?

export  const dataReducer = (state= InitialState , action = null) => {
    switch(action.type) {
    case types.ADD_DATA:
        return Object.assign({}, state, {data:[...state.data, action.payload]});
    case types.REMOVE_DATA:
        return Object.assign({}, state, {data:[]});
    default:
    return state;
    }
}

Upvotes: 2

Views: 2095

Answers (1)

Ming Soon
Ming Soon

Reputation: 1018

You can use the filter method:

export const dataReducer = (state = InitialState, action = null) => {
  switch(action.type) {
    case types.ADD_DATA:
      return Object.assign({}, state, {
        data: [
          ...(state.data.filter(item => (item.id !== action.payload.id))), 
          action.payload
        ]
      });
    case types.REMOVE_DATA:
      return Object.assign({}, state, {
        data: [
          ...(state.data.filter(item => (item.id !== action.payload.id))), 
        ]});
    default:
      return state;
  }
}

Upvotes: 5

Related Questions