esamattis / immer-reducer

Type-safe and terse reducers with Typescript for React Hooks and Redux
http://npm.im/immer-reducer
MIT License
225 stars 15 forks source link

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

Closed richardjli closed 5 years ago

richardjli commented 5 years ago

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?

esamattis commented 5 years ago

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

esamattis commented 5 years ago

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

richardjli commented 5 years ago

Perfect, thanks!