robinvdvleuten / vuex-persistedstate

💾 Persist and rehydrate your Vuex state between page reloads.
https://npm.im/vuex-persistedstate
MIT License
5.77k stars 378 forks source link

Delete persisted state via Nuxt lifecycle hooks #391

Open Jesus82 opened 3 years ago

Jesus82 commented 3 years ago

Relevant code or config In nuxt.js, I'm trying to delete the data in my cart when arriving to the confirmation page.

index.js

export const state = {
  cart: []
}
export const mutations = {
  resetCart (state) {
    Object.assign(state, { cart: []} )
  }
}

/pages/confirmation/index.vue

methods: {
   deleteCart: function() {
      let self = this
      setTimeout(function(){ 
        self.$store.commit('resetCart');
      })
   }
},
mounted() {
    this.deleteCart()
}

What you did:

I wrote a method deleteCart that commits a mutation in order to reset the cart state. Then used mounted nuxt lifecycle hook to fire the method.

What happened:

If no setTimeout is used, the method works, but persistedState acts after that and overwrites with the previous state. Just using setTimeout I am able to reset the state after persitedState.

Problem description:

It is not very cosistent to use a timeout.

Suggested solution:

Is there any event I could use in order to know that persistedState has done its job and then reset the state? Any solution is welcome. Thanks in advance!

jcjp commented 3 years ago

Same issue with you, however for me I do redirection and before I complete my redirection I reset the vuex state to initial state. I do store.commit('RESET') which resets the list of products added to the vuex.

However upon redirection and successful reset, when clicking the back button to return to the website it still retains the product list previously before redirection. Which has been cleared before redirection and should now be an empty.

EDIT: I read the readme of the library and it has an option of fetchBeforeUse set to false by default, I set this to true and it works on my side, so if I clear my localStorage list of products before redirection upon using the back button it will fetch the state of the last localStorage state (which has an empty list of products) it now works properly.