My current goal with VUE is to make the login url
disappear from the navigation bar as soon as the user logs in.
After successfully logging in, the token cookie
is set in the browser. However, the issue arises when the login url
remains visible in the navigation bar until I manually refresh the page. Here are some code snippets to illustrate this:
In Login.vue, the token is set and the user is redirected to the home
page upon logging in:
if(response.status === 200 && response.data.success && response.data.token) {
const token = response.data.token;
this.$cookie.set('token', token);
this.$router.push({name: 'home'});
Then, in Navigation.vue, I check for the existence of the cookie:
<li class="nav-item" v-if="!cookie">
<router-link class="nav-link" to="login">Login</router-link>
</li>
data: () => {
return {
cookie: Vue.cookie.get('token')
}
},
Despite the cookie being set after login, VUE only recognizes it after a manual page refresh using F5. How can I ensure that the login url
disappears immediately upon login?
This is my axios
configuration setup:
const axiosInstance = axios.create({
baseURL: 'http://localhost:3000/',
headers: {'Content-Type': 'application/json'},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
});
axiosInstance.interceptors.request.use(
config => {
config.headers['Authorization'] = 'Bearer '+ Vue.cookie.get('token');
return config;
},
error => Promise.reject(error)
);
EDIT
Could VUEX help me achieve the desired outcome?
EDIT 2
Here's my current solution: I have integrated VUEX to also set the token like this:
this.$cookie.set('token', token);
this.$store.state.cookie = this.$cookie.get('token');
this.$router.push({name: 'home'});
In Navbar.vue, I utilize the following approach:
computed: {
cookie() {
return this.$store.state.cookie
}
},
and then perform this check:
<span v-if="$cookie.get('token') || cookie">
Log out
</span>
<span v-else>
<router-link class="nav-link" to="login">Login</router-link>
</span>
The use of $cookie.get('token') || cookie
allows for seamless checking of the cookie status without requiring a page refresh, while still accommodating scenarios where VUEX state might reset upon refresh, necessitating the use of $cookie.get('token')
.