I believe I'm copying the Todo tutorial pretty much line for line, I am getting this error:
Error: Reducer "addReport" 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.
And here is my addReport reducer:
const addReport = (state = [], action) =>
{
console.log(state)
switch (action.type) {
case ADD_NEW_REPORT:
return [...state,
addReports(undefined, action)
]
}
}
I added the logging statement and can verify that it returns an empty array. Even setting state to something like 1 will produce the same results. What am I missing?
Reducers are functions that take the current state and an action as arguments, and return a new state result. In other words, (state, action) => newState. A Redux app really only has one reducer function: the "root reducer" function that you will pass to createStore later on.
The initial state is zero. Why? Because the second argument to createStore was undefined. This is the state passed to your reducer the first time. When Redux initializes it dispatches a "dummy" action to fill the state. So your counter reducer was called with state equal to undefined.
State, Actions, and Reducers are the building blocks of Redux. Every Redux app has state values, creates actions to describe what happened, and uses reducer functions to calculate new state values based on the previous state and an action. Here's the contents of our app so far: redux-fundamentals-example - CodeSandbox.
combineReducers accepts an object where the key names will become the keys in your root state object, and the values are the slice reducer functions that know how to update those slices of the Redux state. Remember, the key names you give to combineReducers decides what the key names of your state object will be!
You are missing the default
of the switch case.
default: {
return {
...state
}
}
Redux won't play along like a nice kid if you forget to do it!
Or alternatively, you can explicitly return at the end the initial state:
If the state passed to the reducer is undefined, you must explicitly return the initial state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With