This works:
(state, {result}) => {
state.myData = result.data.myData
return state
}
This doesn't work:
(state, {result}) => _.merge(state, result.data)
Somehow the first example triggers a render of my component, but the second doesn't, even if the redux-dev-tools show that data is there.
_.merge is mutative. You should never mutate the state in Redux.
This should work: _.merge({}, state, result.data).
I see, but wasn't my first example mutative too?
It was. It's hard to say why it worked without seeing the whole app. Either way don't mutate the state :-).
I switched to lodash.merge because I wanted to avoid mutation, but then everything broke, haha
Thank you for the quick help :)
@gaearon @kay-is I'm learning much about working in an immutable way. How do you deal with nested objects? _.merge() will not remove objects or key/value pairs.
@chandlervdw can you elaborate on what you would expect _.merge to remove? It's an additive operation, so it shouldn't ever leave you with less than you started with!
@jmeas I just learned that it's additive! So, _.extend() seems to be what I want but I want to ensure that I'm understanding things correctly and am learning the right paradigm. If I've got an object which contains an array of key/value pairs, and I want to update the state of that array upon removal of one of those pairs, is _.extend() the best approach? It works, I just don't see it being used by anyone else in the redux community. What am I missing?
EDIT:
Actually, this isn't what I want. I think I'm going to have to create a new reducer for the nested array because there are other objects and key/value pairs in the top level object that get affected by using _.extend(). Is that the normal paradigm?
Most helpful comment
_.mergeis mutative. You should never mutate the state in Redux.This should work:
_.merge({}, state, result.data).