Skip to content

Commit

Permalink
check for initialization call of redux
Browse files Browse the repository at this point in the history
Reducers get called initialy to return their initial state, this action will probably not pass a filter.
Therefor it is necessary to check for undefined as the given state and return a call to the reducer,
in order to get the reducers state initialzed
  • Loading branch information
timse authored and seantcoyote committed Jan 14, 2018
1 parent 3957e4d commit 3af4991
Showing 1 changed file with 5 additions and 3 deletions.
8 changes: 5 additions & 3 deletions docs/recipes/reducers/ReusingReducerLogic.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ function counter(state = 0, action) {
function createNamedWrapperReducer(reducerFunction, reducerName) {
return (state, action) => {
const {name} = action;
if(name !== reducerName) return state;
const isInitializationCall = state === undefined;
if(name !== reducerName && !isInitializationCall) return state;

return reducerFunction(state, action);
}
Expand All @@ -113,8 +114,9 @@ You could even go as far as to make a generic filtering higher-order reducer:
```js
function createFilteredReducer(reducerFunction, reducerPredicate) {
return (state, action) => {
const shouldRunWrappedReducer = reducerPredicate(action);
return shouldRunWrappedReducer ? reducerFunction(state, action) : state;
const isInitializationCall = state === undefined;
const shouldRunWrappedReducer = reducerPredicate(action) || isInitializationCall;
return shouldRunWrappedReducer ? reducerFunction(state, action) : state;
}
}

Expand Down

0 comments on commit 3af4991

Please sign in to comment.