Last active
April 5, 2018 21:07
-
-
Save mbret/656c889702b064c34cb32c13fa61849f to your computer and use it in GitHub Desktop.
helper to use reduceReducers with combined reducers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { combineReducers } from 'redux' | |
import reduceReducer from 'reduce-reducers' | |
const combineAndIsolateReducers = (reducers) => { | |
const keys = Object.keys(reducers) | |
const combined = combineReducers(reducers) | |
return (state = undefined, action) => { | |
// Important -> slice the needed state so it avoid combineReducers warnings | |
const sliced = {} | |
if (state) { | |
keys.forEach(key => { | |
sliced[key] = state[key] | |
}) | |
} | |
const newState = combined(state === undefined ? undefined : sliced, action) | |
let hasChanged = sliced !== newState | |
// Important -> this part make sure our combinedReducers always | |
// return complete state and not only their parts | |
if (hasChanged) { | |
return { | |
...state, | |
...newState | |
} | |
} else { | |
return state | |
} | |
} | |
} | |
// Your reducer that need to have access to entire state | |
const initialState = { | |
activity: { foo: null } | |
} | |
const activityReducer = (state = initialState, action) => { | |
switch (action.type) { | |
case 'NEW_ACTIVITY': { | |
const subState = state.activity | |
return { | |
activity: { | |
...subState, | |
foo: state.foo ? 'bar' : 'foo' | |
} | |
} | |
} | |
default: | |
return state | |
} | |
} | |
// This is your another reducer that need all the state but is | |
// not on first position | |
// There is a bit of minimum logic to handle because this reducer | |
// is not in charge to initialize the first state | |
const watchReducer = (state, action) => { | |
const {watch} = state | |
const initialState = { | |
...state, | |
watch: {foo: null} | |
} | |
switch (action.type) { | |
case 'NEW_ACTIVITY': { | |
return { | |
...state, | |
watch: { | |
...watch, | |
foo: true | |
} | |
} | |
} | |
default: | |
return watch ? state : initialState | |
} | |
} | |
const reducersA = { | |
a: (state = {}, action) => return state, | |
b: (state = {}, action) => return state, | |
} | |
const reducersB = { | |
c: (state = {}, action) => return state, | |
d: (state = {}, action) => return state, | |
} | |
const rootReducer = reduceReducers( | |
activityReducer, | |
combineAndIsolateReducers(reducersA), | |
combineAndIsolateReducers(reducersB), | |
watchReducer | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment