react The slice reducer for key "mods" returned undefined during initialization. (redux)

Viewed 1939

reducers/index.js

import { combineReducers } from "redux";
import mods from "./mods.js";

export default combineReducers({ // <----- error comes from here
    mods
})

reducers/mods.js

import { GET_MODS } from "../actions/types"

const initialState = {
    mods: [],
}

export default function(state = initialState, action) {
    switch(action.type) {
        case GET_MODS:
            return {
                ...state,
                mods: action.payload
            }
    }
}

No idea why this is happening, I have done similiar things to this but have never encountered this problem, I am new to redux so its probably a stupid mistake...

// The error

Error: The slice reducer for key "mods" 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.

3 Answers

Try with adding the default case,

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_MODS:
      return {
        ...state,
        mods: action.payload
      }
    default:
      return state
  }
}

You probably forgot to include a default case. It could be something like this:

import { GET_MODS } from "../actions/types"

const initialState = {
    mods: [],
}

export default function(state = initialState, action) {
    switch(action.type) {
        case GET_MODS:
            return {
                ...state,
                mods: action.payload
            }
        default:
            return state 
        }
    }
}

I had this same issue, and the problem turned out to be that action.payload was undefined... So I just had to make sure when calling the action that the payload was not undefined.

Related