Home > front end >  why do my redux- persist lose data on reload?
why do my redux- persist lose data on reload?

Time:10-02

I am using redux persist in my web application to store data in localStorage but redux lose data on page reload. does anybody have the same issue or anybody can help me with this.

my redux-persist initialization is:

import { createStore } from "redux";
import userData from "./reducers/reducers";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

const persistConfig = {
  key: "root",
  storage,
  whitelist: ["userData"],
};

const persistedReducer = persistReducer(persistConfig, userData);

const store = createStore(persistedReducer);

export const persistor = persistStore(store);

export default store;

while my index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.scss";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/lib/integration/react";
import { persistor } from "./redux/store";
import store from "./redux/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <PersistGate persistor={persistor}>
        <App />
      </PersistGate>
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

reportWebVitals();

I am unable to find any bug or bad practice can anyone help me.

CodePudding user response:

Redux-persist will handle all the stuff. redux-persist

Example :

configureStore.js

    import { createStore } from 'redux'
    import { persistStore, persistReducer } from 'redux-persist'
    import storage from 'redux-persist/lib/storage' // defaults to localStorage for web and AsyncStorage for react-native
    import rootReducer from './reducers'
    
    const persistConfig = {
      key: 'root',
      storage,
    }
    
    const persistedReducer = persistReducer(persistConfig, rootReducer)
    
    export default () => {
      let store = createStore(persistedReducer)
      let persistor = persistStore(store)
      return { store, persistor }
    }

App.js

import { PersistGate } from 'redux-persist/integration/react'

const App = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <RootComponent />
      </PersistGate>
    </Provider>
  );
};

CodePudding user response:

I don't see anything 'wrong' with your code, the only difference is that you dont have a rootReducer, also you dont need to put a whitelist, since when I used whitelist it didn't filter the others, at least it didn't work for me, what did work for stating which reducer should/shouldn't keep storage was using blackList and passing the reducers that wasnt working.

Try giving a shot creating a rootReducer.

  • Related