Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 736
Camila NieblesR Avatar asked May 15 '18 16:05

Camila NieblesR


2 Answers

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

like image 138
ricardoorellana Avatar answered Oct 08 '22 16:10

ricardoorellana


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

like image 2
andreybleme Avatar answered Oct 08 '22 18:10

andreybleme