Nuxt.js vuex store not persisted

ghz 1years ago ⋅ 288 views

Question

I've got some strange issues with my Nuxt.js Setup. Some States in Store arent persistent, everytime I load another view, they went back to the default value.

pages/test.vue

<template>
  <section class="section">
    <b-container>
      <b-row>
        <b-col cols=12>
          <b-button @click="setTest" variant="dark">test</b-button> | {{this.$store.state.test}} |
        </b-col>
      </b-row>
    </b-container>
  </section>
</template>

<script>
export default {
  name: 'test',
  methods: {
    setTest() {
      this.$store.commit("setTest")
    },
  }
}
</script>

store/index.js

export const state = () => ({
  test: "test"
})

export const mutations = {
  setTest: (state) => state.test = 'Hello'
}

Testscenario is to hit the "test"-button who call the method with mutation- commit "setTest" which set the state to "Hello". Currently it works fine, but if I changed the view or reload the page, the state is set to default "test".

What am I doing wrong?


Answer

Alright, so the behavior is totally logic. Vuex/Pinia are not supposed to be persistent.

For any persistence on the front-end, you need either:

  • cookies
  • localStorage
  • pass it in the URL (query params)
  • IndexedDB
  • get the data back from making a call to a backend

If you are using Vuex or Pinia, there are also packages that you could use to get an easier time (to sync your store into something persistent automatically).

Some of the packages here may be useful: <https://github.com/vuejs/awesome- vue#persistence>

For pinia: https://stackoverflow.com/a/73863929/8816585


If you reload your page with an F5, all your JS will be wiped and loaded again. Hence, no state will be kept since it will be a brand new page. When working with frontend frameworks, you cannot expect it to just work after a page refresh.

Same go when you do follow an href, it is an actual real navigation. What you need to do, is to use a <nuxt-link></nuxt-link> component, with something like to="/profile" to let VueJS move to this URL.

[NuxtLink](https://nuxtjs.org/docs/2.x/features/nuxt-components#the-nuxtlink- component) is a Nuxt.js component and essentially a component on top of <router-link></router-link>, which is Vue router.

TLDR: you cannot use things like window.location.href, nor <a href="...". You may use the given components by either Nuxt (nuxt-link) or Vue's router (router-link), if you're using VueJS only.

Giving a read to the Vue router's documentation may be a good start to understand things a bit more !


If you're using nuxt/auth, give a try to that one: https://auth.nuxtjs.org/api/storage/#universal-storage