championswimmer / vuex-persist

A Vuex plugin to persist the store. (Fully Typescript enabled)
http://championswimmer.in/vuex-persist
MIT License
1.67k stars 117 forks source link

State not loaded before router.forEach when page refreshed #131

Open tmaly1980 opened 5 years ago

tmaly1980 commented 5 years ago

There's a caveat when checking the state in router.forEach (such as to check the user signed in or has a certain role), where the state is not re-loaded from persistent storage yet when router.forEach gets run. This specifically happens when reloading the browser page. The state is still at it's initial state. For example:

router.beforeEach((to, from, next) => {
  if(to.matched.some(record => !record.name == 'login') && !store.state.user) {
    next("/login");
  }
});

This works after the initial page load, but after pressing the browser refresh button, it will unexpectedly kick the user to the login page, even if they've already been logged in.

There's a way around this limitation using store getters that read directly from localstorage/etc (wherever vuex-persist is using for storage), ie:

import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
  storage: window.localStorage
});

export default new Vuex.Store({
  state: { ... },
  plugins: [vuexLocal.plugin],
  getters: {
    isLoggedIn: () => {
        return !!JSON.parse(window.localStorage.getItem('vuex')).user
    }
  }
}); 

The trick is reading from the vuex localStorage directly, ie: JSON.parse(window.localStorage.getItem('vuex')).somekey

It would be great if this could be added to the main README!

morficus commented 4 years ago

There is a work-around for a similar problem when dealing with async data sources. That is in the README: https://github.com/championswimmer/vuex-persist#how-to-know-when-async-store-has-been-replaced

alterhu2020 commented 4 years ago

same issue here when refresh the page in router.beforeEach((to, from, next) => {}, the store cannot get the Getters data. @championswimmer

aislanmaia commented 4 years ago

I was looking for a solution for this.. by refreshing the page the localstorage gets reseted and I don't know where checking for stuffs like if (localstorage.getItem('sdfsf') ....