Camila NieblesR
Camila NieblesR

Reputation: 93

How can I keep the name of user logged vue.js

Im trying to store the user logged on my application. Im using a store.js file to use vuex and save my variables.

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import Cookies from 'js-cookie'


Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    userloged: ''
  }
})

I declared the store variable on my main.js and I used in this way, when I save the name of the user in my login component I use,

        this.$store.state.userloged = this.username;

And when Im going to used in the others components I got it in this way,

 computed:{
    userloged() {
        return this.$store.state.userloged;
    }
},

But if I refresh the page I lost the information. What can I do?

Upvotes: 5

Views: 4274

Answers (3)

ricardoorellana
ricardoorellana

Reputation: 2340

You should use 'vuex-persistedstate' to persist Vuex state with localStorage.

You should update the state through mutations and dispatching an action, redifine your vuex instance to contain the following objects:

import createPersistedState from 'vuex-persistedstate';

const store = new Vuex.Store({
  state: {
    userlogged: ''
  },
  mutations: {
    saveUserLogged (state, loggedUser) {
      state.userLogged = loggedUser
    }
  },
  actions: {
    saveUserLogged (context, loggedUser) {
      context.commit('saveUserLogged', loggedUser)
    }
  },
  plugins: [createPersistedState()]
})

So to save the loggedUser you should dispatch an action:

this.$store.dispatch('saveUserLogged', this.username);

You can learn more about mutations and actions in the Vuex official site

Please take a look to this example https://codesandbox.io/s/0yy7vk29kv

Upvotes: 3

miorey
miorey

Reputation: 946

You can simply use the cookies with https://www.npmjs.com/package/vue-cookies

Upvotes: 0

andreybleme
andreybleme

Reputation: 689

Vuex doesn't persist the state over page reloads.

You have to use something like Vuex-persistedstate plugin.

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})

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

Upvotes: 2

Related Questions