Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Redux reducer think my state is undefined?

Tags:

redux

reducers

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?

like image 537
chum of chance Avatar asked Jun 24 '16 14:06

chum of chance


People also ask

What is a reducer in Redux?

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.

Why is the initial state of my reducer undefined?

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.

What are the building blocks of Redux?

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.

What is combinereducers in Redux?

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!


1 Answers

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.

like image 86
Elod Szopos Avatar answered Oct 13 '22 03:10

Elod Szopos