Reputation: 2602
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
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