esamattis/immer-reducer

Interaction with combineReducers -- how to define default state within a reducer?

richardjli opened this issue · 3 comments

When trying to use this library with redux's combineReducers, I get this error:

Reducer returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.

This is because you're supposed to define your initialState in your reducer, not your createStore function. https://stackoverflow.com/questions/36619093/why-do-i-get-reducer-returned-undefined-during-initialization-despite-pr

How do I define my default state within each reducer?

You can pass it as a second argument to the createReducerFunction:

createReducerFunction(MyImmerReducer, initialStateSlice);

There's also a test for combineReducers:

https://github.com/epeli/immer-reducer/blob/a689705645a121763fbe08e679b2baebe60425ed/__tests__/immer-reducer.test.tsx#L193-L233

I updated the README to use the second arg of the createReducerFunction instead of passing it to createStore. It seems to be more inline with the official redux docs and probably is less confusing for combineReducers users.

https://redux.js.org/recipes/structuring-reducers/initializing-state

Perfect, thanks!