rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 863 forks source link

purge() doesn't work #1015

Open rico345100 opened 5 years ago

rico345100 commented 5 years ago

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.

Trashpants commented 5 years ago

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

chiaberry commented 5 years ago

@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 commented 5 years ago

When I run

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

response comes back as null, is that expected?

Trashpants commented 5 years ago

@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

chiaberry commented 5 years ago

@Trashpants awesome! thank you

jfbloom22 commented 5 years ago

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()
})
marko-ignjatovic commented 5 years ago

When I run

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

response comes back as null, is that expected?

And I am getting undefined

jfbloom22 commented 5 years ago

@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

xyz1hang commented 5 years ago
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 ?

EternalChildren commented 4 years ago

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?

tparesi commented 4 years ago

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

titulus commented 4 years ago
await persistor.purge();
await persistor.purge();

works for me!

karland commented 4 years ago

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.

gleidsonh commented 4 years ago

I just did

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

and works great.

lsmolic commented 4 years ago

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();
manikbajaj commented 4 years ago

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.

gkatsanos commented 4 years ago

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.

bcjohnblue commented 3 years ago

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())])
}
chungmarcoo commented 3 years ago

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();
    }
  };
lsmolic commented 3 years ago

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.

grumpyTofu commented 3 years ago

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);
    });
}
KonstantinZhukovskij commented 2 years ago

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.

suleymanozev commented 2 years ago

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 **/);
jellyfish-tom commented 2 years ago

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

jdavyds commented 1 year ago

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?

nagamejun commented 1 year ago

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.

shubhamGophygital commented 1 year ago

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

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

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

probir-sarkar commented 1 year ago

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

lsmolic commented 1 year ago

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: @.***>

jmathew commented 4 months ago

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