Using Redux-Persist with REST API

Viewed 28

I have followed countless tutorials on redux-persist and believe I am implementing it correct in my redux-toolkit app. However, I think there's a disconnect in fundamental understanding on my end. Can I use persist on an application that uses REST API or do I need to setup my on backend server for it to work? And if you cant use persist for an app that uses REST API, how would I go about getting state to persist on an app that uses Redux-Toolkit? In Application in my browser's devtools, it shows that my state has been saved but when I close the browser window and open it back up, I find that my shopping cart is empty. Here's my code just in case I'm missing something:

Store js

import cartReducer from "./features/Cart/cartSlice"
import modalReducer from "./features/Modal/modalSlice"

//Persist
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";



const persistConfig = {
    key: "persist-key",
    storage
}

const persistedReducer = persistReducer(persistConfig, cartReducer)

const store = configureStore({
    reducer: {
        persistedReducer: persistedReducer,
        cart: cartReducer,
        modal: modalReducer,
    },
    middleware: (getDefaultMiddleware) => getDefaultMiddleware({
        serializableCheck: false
    })
})

const persistor = persistStore(store)

export default store;
export { persistor }

Index js

import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';


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

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

Any help will be appreciated.

1 Answers

Yes you can use redux-persist to able keep data at client side, but keep on mind, you should never keep sensible data. And use it only keep needful data such as session data settings, etc.

You can retrieve all such as normal redux data, handler as useSelector from react-redux library will return your current state.

So your backend not implements nothing to warranty your redux flow, it is entirety responsibility of frontend.

Related