Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-persist got error: Store does not have a valid reducer

I got an error when using redux-persist. I could find few documents about redux-persist v5. And I just follow the official usage example. But I am confused about this. Before I use redux-persist, I can get state from store correctly. But I want to keep login state in local. So I try to use redux-persist. Then I got some problems. Here is my code:

reducer.js

const initialState = {
  isLogin: false,
  uname: "",
}

const userReducer = (state = initialState, action) => {
  switch(action.type) {
    case 'DO_LOGIN':
      return Object.assign({}, state, {
        isLogin: true,
        uname: action.payload.username
      })
    default:
      return state
  }
}

const reducers = combineReducers({
  userInfo: userReducer
})

export default reducers

store.js

import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import { createStore, applyMiddleware, compose } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import reducers from '../reducers'

const loggerMiddleware = createLogger()

const middleware = [thunk, loggerMiddleware]

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const configureStore = composeEnhancers(
  applyMiddleware(...middleware),
)(createStore)

const config = {
  key: 'root',
  version: 1,
  storage,
}

const combinedReducer = persistCombineReducers(config, reducers)

const createAppStore = () => {
  let store = configureStore(combinedReducer)
  let persistor = persistStore(store)

  return { persistor, store }
}

export default createAppStore

App.js

const mapStateToProps = (state) => ({
  logged: state.userInfo.isLogin
})

When I run this code I got this error message TypeError: Cannot read property 'isLogin' of undefined And this error message in console Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

I guess something is not correct when combine reducers. But I have no idea where is wrong?

like image 813
鸡肉味嘎嘣脆 Avatar asked Nov 02 '17 03:11

鸡肉味嘎嘣脆


1 Answers

In the redux-persist docs:

import reducers from './reducers' // where reducers is a object of reducers

the 2nd argument to persistCombineReducers must be an object of reducers.
The export in yout reducer.js should be:

export default {
  reducer: reducer
};

Make the changes and let me know if it solved.

like image 82
Dane Avatar answered Sep 22 '22 10:09

Dane