I am stuck on this from a long time, and none of the online support till now helped much. I am trying to use immer for immutability in my React-Native app. But the reducer part gives an error saying reducer "count" returned undefined during initialization. My count reducer looks like this -
import produce from "immer";
import {
INCREMENT,
DECREMENT,
} from '../action/index.js';
const INITIAL_STATE = {
count: 0,
};
const countReducer = (state, action) =>
produce(state, draft => {
switch (action.type) {
case INCREMENT: {
draft = draft + 1;
break;
}
case DECREMENT: {
draft = draft - 1;
break;
}
}
});
export default countReducer;
My rootReducer is -
import {combineReducers} from 'redux';
import countReducer from './countReducer.js';
const rootReducer = combineReducers({
count: countReducer,
});
export default rootReducer;
How can I fix this?
From the looks of it you are not using INITIAL_STATE
anywhere in your code.
I haven't used immer, but typically you would initialise your state like this
const reducer = (state = initialState, action) => {...}
So I imagine you'd want to do something like:
const INITIAL_STATE = {
count: 0
};
const countReducer = (
state = INITIAL_STATE, // initialises state
action
) =>
produce(state, draft => {
switch (action.type) {
case INCREMENT: {
draft = draft + 1;
break;
}
case DECREMENT: {
draft = draft - 1;
break;
}
}
});