rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.96k stars 866 forks source link

ERROR: Reducer returns undefined for persist/REHYDRATE #1074

Open jarodpeachey opened 5 years ago

jarodpeachey commented 5 years ago

I have redux-persist set up in a personal project, and it's been working up until I tried to create more than one reducer. I checked to make sure I'm not using combineReducers twice, and everything is good there.

I'm getting this error in the console: Uncaught Error: Given action "persist/PERSIST", reducer "mealReducer" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.

Here's my Store.js file:

import thunk from 'redux-thunk';
import { applyMiddleware, compose, createStore } from 'redux';
import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import reducers from './reducers';

const middleware = [thunk];

const persistConfig = {
  key: 'root',
  storage,
  stateReconciler: autoMergeLevel2,
};

const persistCombinedReducers = persistCombineReducers(persistConfig, reducers);

export const store = createStore(
  persistCombinedReducers,
  compose(
    applyMiddleware(...middleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
  ),
);

export const persistor = persistStore(store);

And here's my root reducers file:

import userReducer from './userReducer';
import mealReducer from './mealReducer';
import workoutReducer from './workoutReducer';

const reducers = {
  userReducer,
  mealReducer,
  workoutReducer,
};

export default reducers;

I've tried just about everything, but can't figure out why it's not working with more than one reducer. Like I said before, it previously worked with just the userReducer, but threw the error when I created the mealReducer and workoutReducer (which are basically identical copies of userReducer).

Any help would be appreciated!

lautaro-osacar commented 5 years ago

Have you tried with persistReducer and use redux's combineReducers on your root reducer? Something like:

import { combineReducers } from "redux";
import userReducer from './userReducer';
import mealReducer from './mealReducer';
import workoutReducer from './workoutReducer';

const reducers = combineReducers({
userReducer,
mealReducer,
workoutReducer
});

export default reducers;
jarodpeachey commented 5 years ago

@lautaro-osacar Thanks for replying! I just figured it out. It turns out that even though I had my intialState set to

{
   meals: [],
}

I called a setMeals action from my application file, which set the state to

{
    meals: null,
}

This is where the issue was. Kinda obvious now! 😂