I was stuck in a similar situation sometime back.
So according the redux docs the way you update nested object is :-
function updateVeryNestedField(state, action) {
return {
....state,
first : {
...state.first,
second : {
...state.first.second,
[action.someId] : {
...state.first.second[action.someId],
fourth : action.someValue
}
}
}
}
}
But since you have array in your state it makes you work bit more difficult.
So there are 2 ways in which you can do this.
First way(The hard way)
Create a new object on your own and update the state and return the new state. Now the key here to create a new state object and not assign your current state to the the new object else it would be mutated.
So, create a new object .
const newState ={}
Now assign you current state values which you dont want to change to the new state. Say in your state you have 3 keys , key1
, key2
which you dont want this action to change and shoppingCardReducer
which you want to change.
newState['key1']=//key1 value from current state
newState['key2'] = //key2 value from current state
Now, try following:-
newState['shoppingCardReducer'] ={}
newState['shoppingCardReducer']['products']={}
Now read state.shoppingReducers.products
and sttart looping over your products array and replace that particular element from the state, keep rest intact.
Then return the new state(You should keep rest of properties intact else your app can break)
If you see this is clearly a bad way to do it, not really a hack, reducers do same thing with spread operator but surely a bad way.So I would say try out next option.
Second way(immutablejs)
I would suggest you to use immutable.js. Its really easy and clean to use .
With immutable you can use deleteIn
function to remove your particular particular product element from your state.
data.deleteIn(["shoppingcartReducer",product,//your_to_deleted_element_index])
P.S: I havent tried the above code but with little modification it should work. I hope you get the logic.
Third Method(Normalizr)
You can also try make to normalize your API response to make your data flat and access to access.
But among above three I feel immutable is the best option.