Search code examples
reactjsreduxreact-reduxredux-persist

React-persist is not persisting state


I am trying to implement redux-persist in my reactjs application, i am trying to persist user info but whenever i do refresh all the information is cleaned up and i am redirected to the login page.

store.js

import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import rootReducer from "./state/reducer";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

const persistConfig = {
  key: "primary",
  storage,
  whitelist: ["user", "artist"],
  blacklist: ["alerts"],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const middleWare = [thunk];
const initialState = {};

export const store = createStore(
  persistedReducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleWare))
);

export const persistor = persistStore(store);

index.js for all reducers

import { combineReducers } from "redux";
import artistReducer from "./artistReducer";
import userReducer from "./userReducer";
import alertReducer from "./alertReducer";

export default combineReducers({
  artist: artistReducer,
  user: userReducer,
  alerts: alertReducer,
});

App.js

import { persistor, store } from "./store";
import { PersistGate } from "redux-persist/integration/react";

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <div style={{ backgroundColor: "grey" }}>
          <Router>
            <Fragment>
              <Navbar></Navbar>
              <Alerts></Alerts>
              <Switch> ...{ code continues }

Here i can see my data but on refresh it gets cleaned up enter image description here


Solution

  • After hours of exploring internet i found this issue locked on github [ https://github.com/rt2zz/redux-persist/issues/826#fromHistory ] and there was much voted comment on it by hackrit which states "Hi guys, I found a solution to this problem. (might not apply to all the cases, but worked for me). The problem was caused by my default return in my reducer, which I returned {...state}. Once I changed the default return to just return state, everything work as expected." and this suggestion worked for me.