lucasconstantino / redux-transient

Transient reducers for Redux
MIT License
23 stars 3 forks source link

Integration with combineReducers #2

Open limscoder opened 7 years ago

limscoder commented 7 years ago

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

lucasconstantino commented 7 years ago

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.

limscoder commented 7 years ago

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.