elgerlambert / redux-localstorage

Store enhancer that syncs (a subset) of your Redux store state to localstorage.
MIT License
1.32k stars 107 forks source link

mergePersistedState() does not merge filtered sub objects #61

Open marchaos opened 7 years ago

marchaos commented 7 years ago

if I filter on filter("a.b") and I have an object:

a: {
   b: {hey:"ho"}
}

persisted, and my initial state is:

a: {
  b: {}
  c: {hi: "ho"}
}

c is lost in the merge. I would expect that merge should merge b and c.

VasilyShelkov commented 7 years ago

Hey, I had the same problem, there's a very subtle hint about how to solve this on the readme:

mergePersistedState performs a shallow merge. The following shows how you can easily define a deep merge using e.g. lodash.merge:

const reducer = compose(
  mergePersistedState((initialState, persistedState) => {
    return _.merge({}, initialState, persistedState)
  }),
)(rootReducer);

so in your example you could do something like:

compose(
  mergePersistedState((initialState, persistedState) => ({
    ...initialState,
    ...persistedState,
    a: {
      ...initialState.a,
      ...persistedState.a
    }
  }))
)(
  combineReducers({
    apollo: client.reducer(),
    form: formReducer,
    routing: routerReducer,
    account,
    profile
  })
);
gregorskii commented 6 years ago

Using the more specific mergePersistedState here fixed this issue for me.