Why do I get “Reducer [...] returned undefined during initialization” despite providing initialState to createStore()?
The initialState
argument in createStore()
is often tripping people. It was never meant as a way to “initialize” your application state manually. The only useful applications for it are:
- Booting up server rendered app from JSON state payload.
- “Resuming” the app from a state saved into local storage.
It is implied that you never write initialState
manually and in most apps you don’t even use it. Instead, reducers must always specify their own initial state, and initialState
is just a way to prefill that state when you have an existing serialized version of it.
So this answer is correct: you need to define the initial state in your reducer. Supplying it to createStore()
is not enough, and is not meant to be a way to define the initial state in code.
I had the same error but I didn't include a default case
function generate(state={} ,action) {
switch (action.type) {
case randomNumber:
return {
...state,
random: action.payload
}
default: // need this for default case
return state
}
}
Also, make sure that you are returning the default state last in your reducer. Sometimes you can forget to make sure this is the default for your switch statement (when refactoring and moving around code).
...
default:
return state