React / Redux reducer returned undefined during initialization

I am working on my first React / Redux project. Everything went well, and then I tried to create a new gearbox. I thought it was pretty simple, but when I load the page, I get the error message "Reducer X returned undefined during initialization". The trace says this happens in combReducers (). I found a couple of similar questions, but they did not solve the problem.

On this question: Why do I get "The reducer [...] is returned undefined during initialization", despite providing initialState for createStore ()?

The problem was that they used initialState in createStore (), which I am not doing.

On this question: Why does my Redux reducer consider my state to be undefined?

The problem was the lack of a default return value in the reducer that I have.

My abbreviation code is below. I have console.log () at the beginning and it is not called at all.

reducers / reducer_which_sorter.js

import { SORT_CAMPERS } from '../actions/index'; export default function(state = null, action) { console.log("action is", action); switch(action.which) { case 'recent': case 'alltime': return action.which; break; default: return state; } return state; } 

gearboxes / index.js

 import { combineReducers } from 'redux'; import Campers from './reducer_camper_list'; import ActiveSorter from './reducer_which_sorter'; const rootReducer = combineReducers({ campers: Campers, activeSorter: ActiveSorter }); export default rootReducer; 

Everything compiles fine. No errors from webpack. I have double, triple and quadruple file path checks. I do not see any typos. Can someone see something that I don't see here?

+5
source share
2 answers

The Redux requirement is to use the type property for actions, not which , as you did in your example. Since your console.log check is not being called, the problem may be in another reducer (not listed in your question.)

The reason is that combineReducers calls your reducer functions with a special INIT action type:

 const initialState = reducer(undefined, { type: ActionTypes.INIT }) 

Source: https://github.com/reactjs/redux/blob/master/src/combineReducers.js

Your function, since it includes "action.which" instead of "action.type", returns nothing but undefined.

+2
source

I have console.log () at the beginning and it is not called at all.

It is strange, because the reducer function had to be called at least once with the action @@INIT .

Try testing if your rootReducer is rootReducer called at all. Change it to:

 const rootReducer = (state = {}, action) => { console.log('Test if rootReducer is ever called') return { campers: Campers(state.campers, action), activeSorter: ActiveSorter(state.activeSorter, action) } } 

If it is not called, then the problem is somewhere higher, and not in the reducer itself.

+1
source

Source: https://habr.com/ru/post/1266531/


All Articles