I have a simple SEARCH_SUCCESS
reducer that updates api response into state mapped by id like this:
[searchActionTypes.SEARCH_SUCCESS]: (state, { companies }) => {
return update(state, { $merge: _.indexBy(companies, '_id') })
},
However, because my state is mapped by id, this is replacing any existing companies in state. This is a problem because I want to preserve extra data stored on existing companies in state.
I could just iterate through the companies and manually $merge
state:
const newState = _.deepClone(state)
_.forEach(companies, company => newState[company._id] = state[company._id] ?
update(state[company._id], { $merge: company }) : company
)
return newState
But this feels clunky. Is there a more elegant way to update nested state that will conditionally $merge
or $set
if keys are not present?