redux-transient icon indicating copy to clipboard operation
redux-transient copied to clipboard

Integration with combineReducers

Open limscoder opened this issue 8 years ago • 2 comments

I'm having trouble getting this working with a store that uses combineReducers. Any tips?

limscoder avatar Jun 01 '17 15:06 limscoder

I just added a test to cover this, so you could find usage sample there.

Keep in mind, though, that combineReducers is only a reducer generator which will map a keyed object to reducers for this keys. This means the result of combineReducers os just a valid reducer, no magic involved. redux-transient should then work fine with it.

Ps.: you can't add a transient reducer generated via combineReducer because by default combineReducer will exclude any other non-mapped keys, meaning your reducer would probably purge other non-related state.

lucasconstantino avatar Jun 01 '17 17:06 lucasconstantino

I figured out a bit of a workaround to avoid problems with non-mapped keys.

I initially call combineReducer with an empty function like this:


combineReducer({
  transientBranch: (state = '__transient__') => state
});

Then my transient reducer looks like this:


function transientReducer(state, action) {
    const stateValue = state[stateKey];
    const initializedStateValue = stateValue === '__transient__'
      ? undefined : stateValue;
    const newState = {
      ...state,
      [stateKey]: reducer(initializedStateValue, action),
    };

    return newState;
  };

This allows transientReducer to be added at runtime without any key errors or overwriting from combineReducer.

limscoder avatar Jun 01 '17 21:06 limscoder