As I develop a Single Page Application (SPA), I am utilizing Vuex to manage session states on the client side. However, I have noticed that the state resets whenever the browser is manually refreshed. Is there a way to prevent this behavior without relying solely on local storage? And if using local storage is necessary, how can I access the initial state stored there?
Navbar Component
<template>
<div>
<ul v-if="!isLogued">
<router-link :to="{ name:'login'}" class="nav-link">Login</router-link>
</ul>
<ul v-if="isLogued">
<a href="#" class="nav-link">Profile</a>
<a href="" @click.prevent="logout">Logout</a>
</ul>
</div>
</template>
<script>
import {mapState,mapMutations } from 'vuex';
export default{
computed : mapState(['isLogued']),
methods:{
...mapMutations(['logout']),
}
}
</script>
Store.js
export default {
state: {
userLogued: {},
api_token : '',
isLogued : false
},
mutations: {
login( state){
state.userLogued = JSON.parse(localStorage.getItem('usuario'));
state.api_token = localStorage.getItem('api_token');
state.isLogued = true
},
logout(state){
state.userLogued = {}
state.isLogued = false
state.api_token = null
localStorage.clear()
}
}
};
App.JS
Vue.use(VueRouter)
Vue.use(Vuex)
import store from './vuex/store';
import routes from './routes';
const router = new VueRouter({
mode: 'history',
routes
})
const app = new Vue({
router,
store : new Vuex.Store(store)
}).$mount('#app')
Within my login component, after making a successful Axios POST request, I handle the response as follows:
methods : {
...mapMutations(['login']),
sendLogin(){
axios.post('/api/login' , this.form)
.then(res =>{
localStorage.setItem('api_token', res.data.api_token);
localStorage.setItem('user_logued', JSON.stringify(res.data.usuario));
this.login();
this.$router.push('/');
})