11

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?

chum of chance
  • 6,200
  • 10
  • 46
  • 74

1 Answers1

30

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.

Elod Szopos
  • 3,475
  • 21
  • 32
  • 1
    Interestingly this answer helped me because I was setting an object but returning simply "state" in my default. I wasn't aware you need to send a default state in the same format as the initial state. This doesn't appear to be the case if the initial state is an array or string etc. – Matt Saunders Oct 18 '17 at 11:50
  • For me, this as well as a syntax error (incomplete assignment line) caused the reducer to not load the state properly. Thanks! – RoboBear Feb 27 '20 at 05:50