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

How to access req object in vuex-persistedstate plugin function #129

Closed o1lab closed 6 years ago

o1lab commented 6 years ago

Using latest version : 2.5.1

Is there a way to access request object in vuex-persistedstate plugin function.

Im building social authorization in nuxt and on successfull authorization from express - the user object is stored in request. And this user object has to be committed to store and to localstorage.

nuxt.config.js { src: '~plugins/localStorage.js', ssr: false },

middleware/localStorage.js

import createPersistedState from 'vuex-persistedstate'

export default ({store, isHMR}) => {
  // In case of HMR, mutation occurs before nuxReady, so previously saved state
  // gets replaced with original state received from server. So, we've to skip HMR.
  // Also nuxtReady event fires for HMR as well, which results multiple registration of
  // vuex-persistedstate plugin
  if (isHMR) return

  if (process.client) {
    window.onNuxtReady((nuxt) => {
      createPersistedState()(store) // vuex plugins can be connected to store, even after creation
    })
  }

}
robinvdvleuten commented 6 years ago

This sounds like a specific use-case for your project's setup. Unfortunately, I do not have the time to dive into such questions. Please go to StackOverflow or spectrum.chat to look for help.

o1lab commented 6 years ago

For those who come across this problem - as a workaround I have now a middleware which checks the user state in store. If it is null then it makes an api call to get data from express-server and commit it to store. This way any data in request object can be persisted to vuex-persistedstate

middleware/auth.js

export default async function ({context, store, route, redirect, req}) {

  if (process.client && store.getters.User === null) {
    console.log('Middleware in in client, user data is null: get user data');
    let user = await store.$axios.get('/users/me');
    if (user && user.data ) {
      store.commit('SET_USER', user.data);
    } 
  }

}
simon-zhangmuye commented 5 years ago

I have a similar problem just like you. I guess the problem may because, when I refresh the page, vue deletes store in vuex and middleware is loaded before vue persist sets values to vuex.