Lun
Lun

Reputation: 1131

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

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.

Upvotes: 3

Views: 7167

Answers (3)

big boy
big boy

Reputation: 395

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.

Upvotes: 1

M3rt
M3rt

Reputation: 388

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
  }
}

Upvotes: 9

Ryan Le
Ryan Le

Reputation: 8412

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 
        }
    }
}

Upvotes: 4

Related Questions