How to keep user logged in using vuex?

by muriel.schmidt , in category: Javascript , 9 months ago

How to keep user logged in using vuex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 9 months ago

@muriel.schmidt 

To keep a user logged in using Vuex, you can store the user's authentication token in the Vuex store after they log in. You can then check if the token exists in the store on page load and automatically log the user in if it does. Here are the steps to keep a user logged in using Vuex:

  1. Create a Vuex module for authentication:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    isAuthenticated: false,
    token: null
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      state.isAuthenticated = true;
    },
    removeToken(state) {
      state.token = null;
      state.isAuthenticated = false;
    }
  },
  actions: {
    login({ commit }, token) {
      commit('setToken', token);
    },
    logout({ commit }) {
      commit('removeToken');
    }
  }
});


  1. After a successful login, store the authentication token in the Vuex store:
1
this.$store.dispatch('login', token);


  1. On page load, check if the user is already authenticated by checking if the token exists in the Vuex store:
1
2
3
4
const token = this.$store.state.token;
if (token) {
  // Automatically log the user in here
}


  1. To keep the user logged in between page refreshes, you can also store the authentication token in localStorage or sessionStorage:
1
localStorage.setItem('token', token);


  1. After a page refresh, check if the token exists in localStorage and use it to automatically log the user in again:
1
2
3
4
const token = localStorage.getItem('token');
if (token) {
  // Automatically log the user in here
}


By following these steps, you can keep a user logged in using Vuex and ensure they stay authenticated between page loads and refreshes.