1

In the official documentation it says to add an extra reducer in order to purge the state of the current slice, however there is no a clear example everywhere

import { PURGE } from "redux-persist";

extraReducers: (builder) => {
  builder.addCase(PURGE, (state) => {
    customEntityAdapter.removeAll(state);
  });
}

How to import or where did it get customEntityAdapter, when I call the persistorObject then purge it shows error, anybody can give me some light on this, thanks I appreciate clear example with redux-toolkit with https://redux-toolkit.js.org/usage/usage-guide#use-with-redux-persist

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Chris David
  • 31
  • 1
  • 4
  • ` persistor.purge().then(() => { persistor.flush(); persistor.pause(); persistor.persist(); });` Only this worked for me – Sayyed Dawood Jun 22 '23 at 11:16

7 Answers7

4

As Radu Lunasu said, this is the correct code:

extraReducers: (builder) => {
  builder.addCase(PURGE, () => {
    return initialState;
  });
},

Then you can use persistor.purge() in any component, for exaple:

const handleLogout = () => {
    persistor.purge();
    navigate("/login");
};

I don't have the reputation to upvote your answer. Sorry, but +1

Maxi Bora
  • 41
  • 3
0

customEntityAdapter, according to its name, it should be created by createEntityAdapter.

A function that generates a set of prebuilt reducers and selectors for performing CRUD operations

Whether it is used or not has nothing to do with using redux-persist. Since your question is about how to use RTK and redux-persist, and its purge state function, in order to simplify the problem, I will not use createEntityAdapter.

An example about how to use RTK with redux-persist and .purge() method on persistor.

App.tsx:

import "./styles.css";
import { persistor } from "./store";

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button
        onClick={() => {
          persistor.purge();
        }}
      >
        purge state
      </button>
    </div>
  );
}

reducers.ts:

import { combineReducers } from "@reduxjs/toolkit";

const rootReducer = combineReducers({
  user: (state = { name: "teresa teng" }, action) => state
});

export default rootReducer;

store.ts:

import { configureStore } from "@reduxjs/toolkit";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER
} from "redux-persist";
import storage from "redux-persist/lib/storage";

import rootReducer from "./reducers";

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

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER]
      }
    })
});

let persistor = persistStore(store);

export { store, persistor };

index.tsx:

import { render } from "react-dom";
import { Provider } from "react-redux";
import { PersistGate } from "redux-persist/integration/react";

import { store, persistor } from "./store";

import App from "./App";

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

The state persisted in the default storage engine - localStorage:

enter image description here

You can click the button, purge the state from localStorage.

codesandbox

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • this doesn't purge data from memory, only from localStorage. It is the aim of the PURGE case in extraReducers to delete the data in the memory store – spezzino Mar 16 '22 at 08:16
0

Adding to @slideshowp2 answer's the extra reducer to purge should match the config used to persist the state. Change customEntitiyAdapter to storage mode specified in the persistConfig, which in this case is storage, change removeAll to remove, and speciify the key from the same persistConfig. If the persistConfig is this

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

change

import { PURGE } from "redux-persist";

extraReducers: (builder) => {
  builder.addCase(PURGE, (state) => {
    customEntityAdapter.removeAll(state);
  });
}

to

import { PURGE } from "redux-persist";

extraReducers: (builder) => {
  builder.addCase(PURGE, (state) => {
    storage.remove("root");
  });
}
Somto
  • 23
  • 6
0

The way that I approached this using AsyncStorage and redux-persist was to call the persistor.purge() when the user clicks to sign out, and then in the extraReducers add a case for PURGE that returns the inial state for each slice that you want to remove. redux-persist saves everything under the persist:root key in local storage.

import AsyncStorage from '@react-native-async-storage/async-storage';
import { PURGE } from 'redux-persist';
...

extraReducers: builder => {
  builder
   .addCase(PURGE, () => {
     // When user logs out, clear the store
     AsyncStorage.removeItem('persist:root');
     return initialState;
   })
 }
Artan M.
  • 817
  • 1
  • 11
  • 16
0

The easiest way is to use :

import { persistStore } from 'redux-persist';

const store = {}

const persistor = persistStore(store);

export const purgeData = async () => {
  await persistor.purge();
};
-1

man, I did this and it worked. put this thing in your slice:

import { PURGE } from "redux-persist";

extraReducers: (builder) => {
  builder.addCase(PURGE, (state) => {
    customEntityAdapter.removeAll(state);
  });
}

then create a function in any component:

const purge = () => {
    persistor.purge()
}

use it where you need it:

<button onClick={purge}>Purge</button>
morphine
  • 1
  • 1
-1

that's just example code to reset state to initial state. would be clearer if written like this:

  extraReducers: (builder) => {
    builder.addCase(PURGE, (state) => {
      return initialState;
    });
  },

remember, a reducer returns the new state therefore, after a purge, you would return the initial state or an empty state.

Radu Luncasu
  • 975
  • 10
  • 17