Vuex state on page refresh

boomboxboy picture boomboxboy · Mar 26, 2017 · Viewed 84.7k times · Source

My app uses the Firebase API for User Authentication, saving the Login status as a boolean value in a Vuex State.

When the user logs in I set the login status and conditionally display the Login/Logout button accordingly.

But when the​ page is refreshed, the state of the vue app is lost and reset to default

This causes a problem as even when the user is logged in and the page is refreshed the login status is set back to false and the login button is displayed instead of logout button even though the user stays logged in....

What shall I do to prevent this behavior

Shall I use cookies Or any other better solution is available...

    -

Answer

sobolevn picture sobolevn · Mar 26, 2017

This is a known use case. There are different solutions.

For example, one can use vuex-persistedstate. This is a plugin for vuex to handle and store state between page refreshes.

Sample code:

import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      getState: (key) => Cookies.getJSON(key),
      setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
    })
  ]
})

What we do here is simple:

  1. you need to install js-cookie
  2. on getState we try to load saved state from Cookies
  3. on setState we save our state to Cookies

Docs and installation instructions: https://www.npmjs.com/package/vuex-persistedstate