Dennis
Dennis

Reputation: 158

How do i do redux persist in react.js

im working on a project where i want to persist redux state for my cart but seems to be missing some thing. this is my store:

import { createStore } from "redux";
import counterReducer from "../store/reducers/reducers";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage"; // defaults to localStorage for web

// const store = createStore(counterReducer);

// export default store;

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, counterReducer);

export default () => {
  let store = createStore(persistedReducer);
  let persistor = persistStore(store);
  return { store, persistor };
};

and this is my index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import "bootstrap/dist/css/bootstrap.min.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { Provider } from "react-redux";
import store from "./store/";
import persistor from "./store/";
import { PersistGate } from "redux-persist/integration/react";

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

serviceWorker.unregister();

this is the error im getting when i try to run my app:

TypeError: store.getState is not a function
(anonymous function)
C:/Users/Denoh/wasilisha/Wasilisha_Africa/node_modules/react-redux/es/components/Provider.js:19
  16 |   };
  17 | }, [store]);
  18 | var previousState = useMemo(function () {
> 19 |   return store.getState();
     | ^  20 | }, [store]);
  21 | useEffect(function () {
  22 |   var subscription = contextValue.subscription;
View compiled
mountMemo
C:/Users/Denoh/wasilisha/Wasilisha_Africa/node_modules/react-dom/cjs/react-dom.development.js:15442
  15439 | function mountMemo(nextCreate, deps) {
  15440 |   var hook = mountWorkInProgressHook();
  15441 |   var nextDeps = deps === undefined ? null : deps;
> 15442 |   var nextValue = nextCreate();
  15443 |   hook.memoizedState = [nextValue, nextDeps];
  15444 |   return nextValue;
  15445 | }

please help me locate my error. when i try to use my redux store without the persist library, everything works fine. but with the persist, i cant trace where my error is.

Upvotes: 0

Views: 641

Answers (1)

phry
phry

Reputation: 44078

your store file exports a buildStore function, not store and persistor.

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


const {store, persistor} = buildStore()

ReactDOM.render(

Always keep in mind that a file can have only one default export, so if you use the default import syntax for the same file for two different things, something is fishy ;)

Upvotes: 2

Related Questions