Search code examples
javascriptreactjsreduxstore

If the state passed to the reducer is undefined,you must explicitly return the initial state


I'm new on react redux and i got an error like on the below enter image description here

and here is my store.js:

import { applyMiddleware, combineReducers, createStore } from "redux"
import thunk from "redux-thunk"
import {composeWithDevTools} from "redux-devtools-extension"
import authReducer from "./reducers/auth"


const initialState = {

}


const reducers = combineReducers({
    auth: authReducer
})

const store = createStore(reducers,initialState, composeWithDevTools(applyMiddleware(thunk)))


export default store

and here is my auth reducer:

const authReducer = (state = {auth:null}, action) =>{

switch (action.type) {
    case "REGISTER":
        localStorage.setItem('auth',JSON.stringify(action.payload))
        return{
            ...state,
            auth:action.payload
        }
    case "LOGIN":
        localStorage.setItem('auth',JSON.stringify(action.payload))
        return{
            ...state,
            auth: action.payload
        }
    case "LOGUT":
        localStorage.clear()
        return{
            ...state,
            auth: null
        }
    default:
        break;
}

}

export default authReducer

I wanted to take an login form datas but i got error like this. If anyone can help me I will appreciate


Solution

  • I think you need to return state in default so it doesn't return undefined.

    default:
        return state;