Error: Reducer "counter" returned undefined during initialization. If the state passed to the reducer is undefined

Viewed 2058

I'm trying to do a basic test of reduxer(Learning) and it seems basic with no problem but I get this error"× Error: Reducer "counter" 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. If you don't want to set a value for this reducer, you can use null instead of undefined."

I believe the response is very stupid hope for help.

Reduxer file. counter.js

const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
  }
};

export default counterReducer;

isLogged.js

const loggedReducer = (state = false, action) => {
  switch (action.type) {
    case "SING_IN":
      return !state;
    default:
      return state;
  }
};
export default loggedReducer;
index.js

import counterReducer from "./counter";
import loggedReducer from "./isLogged";
import { combineReducers } from "redux";

const allReducers = combineReducers({
  counter: counterReducer,
  isLogged: loggedReducer,
});

export default allReducers;

src folder>index.js.

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { createStore } from "redux";
import allReducer from "./reducers";

const store = createStore(
  allReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);


serviceWorker.unregister();

2 Answers

You should return by default from reducer

const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1;
    case "DECREMENT":
      return state - 1;
    default:
      return state;
  }
};

Every reducer receives every action dispatched. If you don't know the action type you should return the state untouched.

 const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1
    case "DECREMENT":
      return state - 1
    default:
      return state // Don't ever forget to add a Default case.
  }
}

Don't ever forget to add a Default case..., because if the state passed to the reducer is undefined.

Related