redux-persist icon indicating copy to clipboard operation
redux-persist copied to clipboard

purge() doesn't work

Open rico345100 opened this issue 6 years ago • 30 comments

Hello. Using persistor.purge doesn't clear any data in my storage.

Here's the code:

const persistor = getPersistor();
await persistor.purge();

getPersistor() function returns persistor, and I called purge function but still nothing changed in my storage.

I also tried this code as well, but doesn't worked either:

const persistor = getPersistor();
await persistor.purge();
await persistor.flush();
await persistor.persist();

It seems like purge doesn't work. Used @5.10.0.

rico345100 avatar Mar 28 '19 10:03 rico345100

I was confused by this too - not sure if you fixed it by now, but for any people who stumble across this in the future: in order for this to work you have to make sure there is a PURGE action for each reducer that returns your 'clean' state. Then your commands of purge(), flush() will clear and force save the changes.

For reference I am coding with react-native (so I assume this is the same for react)

what's confusing is that if you immediately call purge() after setting up the persistor in store.js it will clear it on boot as expected

Trashpants avatar Apr 18 '19 08:04 Trashpants

@Trashpants, can you elaborate on what a PURGE action is for each reducer? Is the data being erased from the disk, but not in redux? I cannot tell if I'm running into the same issues you are describing. thanks in advance

chiaberry avatar May 21 '19 17:05 chiaberry

When I run

persistor.purge()
     .then(response => console.log(response))

response comes back as null, is that expected?

chiaberry avatar May 21 '19 17:05 chiaberry

@chiaberry I have multiple reducers implemented with a PURGE case as

import { PURGE } from "redux-persist";

const INITIAL_STATE = {
  token: "",
  loading: false,
  user: {}
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case PURGE:
      return INITIAL_STATE;
    }
 };

that way when I call persistor.purge() its actually setting my state back to INITIAL_STATE

Trashpants avatar May 21 '19 17:05 Trashpants

@Trashpants awesome! thank you

chiaberry avatar May 21 '19 17:05 chiaberry

I was having a similar issue, but after I implemented perge() I was still having issues. It turned out to be a race condition where some other action would write to state and trigger persisting data that I expected to be cleared. If a user logged out while an API call was loading, it would cause fun issues. I ended up with:

persistor.purge()
.then(() => {
return persistor.flush()
})
.then(() => {
persistor.pause()
})

jfbloom22 avatar May 22 '19 18:05 jfbloom22

When I run

persistor.purge()
     .then(response => console.log(response))

response comes back as null, is that expected?

And I am getting undefined

marko-ignjatovic avatar Jun 07 '19 13:06 marko-ignjatovic

@lolz42 that is expected. The function does not return anything besides a promise. https://github.com/rt2zz/redux-persist/blob/f6f6d642fb3e3f32544189a336442726344f323a/src/persistStore.js#L95

jfbloom22 avatar Jun 12 '19 13:06 jfbloom22

persistor.pause()
persistor.flush().then(() => { return persistor.purge() })

and then depends on your app logic resume it by persistor.persist()

e.g in login page ?

xyz1hang avatar Jun 19 '19 10:06 xyz1hang

i have the same problem. when i upgrade the app the redux state is older. i think the persistStore make it. but nothing happened after persistor.purge()

persistor.pause()
persistor.flush().then(() => { return persistor.purge() })

not work for me. who have the better solutions?

EternalChildren avatar Nov 12 '19 09:11 EternalChildren

I ran into a similar situation and need to enable remote debugging to have resistor.purge() work as expected on React Native using expo.

tparesi avatar Nov 14 '19 19:11 tparesi

await persistor.purge();
await persistor.purge();

works for me!

titulus avatar Dec 18 '19 12:12 titulus

Works for me:

    const purge = () => {
      persistor.purge()
      console.log("Factory reset performed.")
    }

    <button onClick={() => purge()} >Purge</button>

Does NOT work for me:

    const purge = () => {
      persistor.purge()
      console.log("Factory reset performed.")
    }

    purge()

Also does NOT work for me:

    const purge = async () => {
      await persistor.purge()
      console.log("Factory reset performed.")
    }

    purge()

Solution from @titulus also works for me

    const purge = async () => {
      await persistor.purge()
      await persistor.purge()
      console.log("Factory reset performed.")
    }

    purge()

Alternative solution also works for me:

    const purge = () => {
      persistor.purge()
      console.log("Factory reset performed.")
    }

    setTimeout(() => purge(), 200)

I played around with the delay and it seems to need at least 100ms.

karland avatar Apr 13 '20 01:04 karland

I just did

setTimeout(() => persistor.purge(), 200)

and works great.

gleidsonh avatar Apr 14 '20 18:04 gleidsonh

in all seriousness, I think I found the fix. You all want me to submit a PR?

// FiXeD iT
await persistor.purge();
await persistor.purge();
await persistor.purge();
await persistor.purge();
await persistor.purge();
await persistor.purge();
await persistor.purge();

lsmolic avatar May 12 '20 00:05 lsmolic

Strangely it's working with a setTimeout() as posted by @gleidsonh. This needs to be fixed. I was using this in generator with yield in redux-saga and yet somehow promise doesn't return true.

setTimeout(() => persistor.purge(), 200)

I just did

setTimeout(() => persistor.purge(), 200)

and works great.

manikbajaj avatar May 27 '20 11:05 manikbajaj

I don't understand most of the comments. persistore.purge() as it's clearing localStorage has to be a promise / async. You can await it inside an async function and I'd use a try/catch as well:

export let logout = () => async (dispatch) => {

  try {
    await persistor.purge();
    dispatch(logoutSucceed());
  } catch (err) {
    dispatch(logoutFailed(err));
  }
};

I assume just doing persister.purge() without awaiting or without .then(() => /*do something*/) isn't gonna work. I guess the documentation could have some more examples.

gkatsanos avatar Jul 07 '20 14:07 gkatsanos

I am implement redux-persist with redux-saga. I found it clear the localStorage and redux state all together well.

redux-persist version: 6.0.0

import { persistor } from 'src/store' // Self create persistor

export function* logoutSaga() {
  // logoutRequestSuccess() is responsible for clearing the redux state
  yield all([call(persistor.purge), put(logoutRequestSuccess())])
}

bcjohnblue avatar Aug 14 '20 03:08 bcjohnblue

I was faced this kind of problem yesterday, and keep finding the solution across Google / Stack Overflow. And below is my solution that works fine now for people who is stilling struggling right now. My problem that I need to get through yesterday is my redux-persist is not working after my rootReducer reset by return rootReducer(undefined, action);. And here is my solution in my LogoutScreen (i.e. in stack navigation), and my store.js no need to change the original code (i.e. return rootReducer(undefined, action);)

const logoutEffect = () => {
    const {error, success} = authState.remotes.logout;
    if (error || success) {
      dispatch(logoutReset());

      persistor.pause();
      persistor.flush().then(() => {
        return persistor.purge();
      });

      // navigation.navigate('Welcome');
      navigation.dispatch(
        CommonActions.reset({
          index: 1,
          routes: [{name: 'Welcome'}],
        }),
      );

      persistor.persist();
    }
  };

chungmarcoo avatar May 21 '21 03:05 chungmarcoo

Lol. Read the docs. It’s a callback, not a promise. Add a timeout and just do the purge after 1 second.

On May 20, 2021, at 21:24, chungmarcoo @.***> wrote:

 I was faced this kind of problem yesterday, and keep finding the solution across Google / Stack Overflow. And below is my solution that works fine now for people who is stilling struggling right now. My problem that I need to get through yesterday is that my redex-persist is not working atfer my rootReducer reset by return rootReducer(undefined, action);. And here is my solution in my LogoutScreen (i.e. in stack navigation), and my store.js no need to change the original code (i.e. return rootReducer(undefined, action);)

` const logoutEffect = () => { const {error, success} = authState.remotes.logout; if (error || success) { dispatch(logoutReset());

persistor.pause(); persistor.flush().then(() => { return persistor.purge(); });

navigation.dispatch( CommonActions.reset({ index: 1, routes: [{name: 'Welcome'}], }), );

persistor.persist(); } }; `

— You are receiving this because you commented. Reply to this email directly, view it on GitHub, or unsubscribe.

lsmolic avatar May 21 '21 03:05 lsmolic

credit to @Trashpants for the hint, but for those of my fellow Redux Toolkit fans, you need to add an 'extraReducer' on your slice.

import { PURGE } from "redux-persist";

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

grumpyTofu avatar Jun 30 '21 20:06 grumpyTofu

This example is for those who use react-native. But I'm pretty sure it will work the same for react.

You must reload your application, this is the whole solution. You take the NativeModules from react-native

persistor.purge().then(() => NativeModules.DevSettings.reload());

This works great.

KonstantinZhukovskij avatar Jul 30 '21 13:07 KonstantinZhukovskij

This method is applicable for those who use Redux Toolkit. The extraReducers method in each slice should contain:

 builder.addCase(PURGE, () => initialState);

Example

import { PURGE } from "redux-persist";
import { AuthUser } from "../types/user";
import { createSlice } from "@reduxjs/toolkit";

export interface AuthState {
  user: AuthUser | null;
  token: string | null;
}

const initialState: AuthState = {
  user: null,
  token: null,
};

const slice = createSlice({
  name: "auth",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(PURGE, () => initialState); // THIS LINE
  },
});

Purge Usage:

persistor.purge().then(() => /** whatever you want to do **/);

suleymanozev avatar Apr 14 '22 01:04 suleymanozev

@suleymanozev thank you thousand times and more kind sir. Saved me :)

jellyfish-tom avatar May 18 '22 19:05 jellyfish-tom

credit to @Trashpants for the hint, but for those of my fellow Redux Toolkit fans, you need to add an 'extraReducer' on your slice.

import { PURGE } from "redux-persist";

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

Whe is the customEntityAdapter importing from?

jdavyds avatar Sep 14 '22 00:09 jdavyds

Whe is the customEntityAdapter importing from?

https://stackoverflow.com/questions/68929107/how-to-purge-any-persisted-state-using-react-tool-kit-with-redux-persist

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

nagamejun avatar Sep 19 '22 01:09 nagamejun

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

const clearPersistData=()=>{ persistor.pause(); persistor.flush().then(() => { return persistor.purge(); }); }

this worked for me !!!! @chungmarcoo thanks for the help

shubhamGophygital avatar Jan 17 '23 08:01 shubhamGophygital

// To clear persisted state data and immediately flush the storage system: persistor.purge().then(() => persistor.flush());

probir-sarkar avatar Feb 19 '23 17:02 probir-sarkar

Unless it's been updated, the purge is not a promise, so that will not work. Any positive test cases are just my coincidence.It is a callback and must be handled by passing a function which will execute asynchronously. If you read the source code it will confirm this.

On Sun, Feb 19, 2023 at 11:10 AM Probir Sarkar @.***> wrote:

// To clear persisted state data and immediately flush the storage system: persistor.purge().then(() => persistor.flush());

— Reply to this email directly, view it on GitHub https://github.com/rt2zz/redux-persist/issues/1015#issuecomment-1436041126, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAEFV3ACHIOIUSP6E4QU7XDWYJHY3ANCNFSM4HB7IJOQ . You are receiving this because you commented.Message ID: @.***>

lsmolic avatar Feb 19 '23 18:02 lsmolic

Unless it's been updated, the purge is not a promise, so that will not work. Any positive test cases are just my coincidence.It is a callback and must be handled by passing a function which will execute asynchronously. If you read the source code it will confirm this.

This source indicates its a promise: https://github.com/rt2zz/redux-persist/blob/d8b01a085e3679db43503a3858e8d4759d6f22fa/src/persistStore.ts#L91

And it seems to have been for the past 6 years: https://github.com/rt2zz/redux-persist/blame/9526af76e3e64cfe9a55a6c91386349e8dc7a96f/src/persistStore.js#L79

jmathew avatar Mar 26 '24 01:03 jmathew