Redux: Merging state with lodash

Created on 5 Aug 2015  路  7Comments  路  Source: reduxjs/redux

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.

Most helpful comment

_.merge is mutative. You should never mutate the state in Redux.
This should work: _.merge({}, state, result.data).

All 7 comments

_.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?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ms88privat picture ms88privat  路  3Comments

dmitry-zaets picture dmitry-zaets  路  3Comments

jimbolla picture jimbolla  路  3Comments

amorphius picture amorphius  路  3Comments

timdorr picture timdorr  路  3Comments