I recently started using vue js to develop applications. I have successfully implemented a function that logs in the user by storing tokens received from the back-end in local storage, and checks for token validity. Everything was working fine until I decided to incorporate vuex to access user status anywhere in the app. However, I am facing an issue where the view is not updating after state changes. I have spent several hours troubleshooting with no luck. Is there a way to update the view without having to refresh the page?
Below is a snippet of the code I am currently working on. While it may seem like a jumble of variables displayed on screen, it is purely for testing purposes:
In my component
<p>Current token : {{ tokenToCheck }}</p>
<p>{{ isValid }}</p>
<p>{{ loggedIn }}</p>
<p> {{ test }} </p>
<div class="alert alert-success" v-if="loggedIn"><p>You are logged in</p></div>
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import jwt from 'jsonwebtoken'
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
tokenToCheck: localStorage.getItem('token'),
isValid: 'test',
isLogged: true
},
getters: {
isLogged: (state) => {
return state.isLogged;
}
},
mutations: {
CHECK_TOKEN(state) {
try{
jwt.verify(state.tokenToCheck, 'RANDOM_TOKEN');
state.isValid = 'ok';
state.isLogged = true;
return true;
} catch(error) {
console.log(error);
console.log(state.tokenToCheck);
console.log('erreur test token');
state.isValid = "expiry";
state.isLogged = false;
return false;
}
}
}
});
Computed properties in my component
export default {
name: 'Home',
data() {
return {
pseudo: '',
test: localStorage.getItem('token'),
password: '',
errorMessage:'',
token: '',
isAlert: false
}
},
computed: {
loggedIn() {
return this.$store.getters.isLogged;
},
isValid(){
return this.$store.state.isValid;
},
tokenToCheck() {
return this.$store.state.tokenToCHeck;
}
},
mounted() {
this.$store.commit('CHECK_TOKEN');
},
Note: There are no errors showing up in the console, and the secret key used is different than what is mentioned here.