I am facing an issue where the middleware renders before Vuex when the page is reloaded. This causes a problem as I need to change a value in Vuex based on the user's authentication status. Due to this sequence, the middleware returns the initial value of Vuex first. As a result, if the user is authenticated, it initially shows false and then true after Vuex is rendered. By that time, the middleware has already finished loading, leading to redirecting the user to the login page whenever the page is refreshed. Is there a way to prioritize loading Vuex before the middleware?
Here is the middleware code:
export default async function ({ store, redirect }) {
// If the user is not authenticated
const authenticated = await store.state.signup.authenticated
if (!authenticated) {
console.log(!authenticated)
return redirect('/login')
} else {
console.log('I am logged in')
}
}
Here is the Vuex code:
import axios from 'axios'
export const state = () => ({
authenticated: false,
credential: null,
})
export const mutations = {
ADD_USER(state, data) {
state.credential = data
state.authenticated = true
},
LOGOUT(state) {
state.credential = null
state.authenticated = false
},
}
export const actions = {
async addUser({ commit }, data) {
try {
const response = await axios.post(
'http://localhost:8000/api/rest-auth/registration/',
data
)
commit('ADD_USER', response.data)
this.$router.push('/')
} catch (error) {
return console.log(error)
}
},
async addUserLogin({ commit }, data) {
try {
const response = await axios.post(
'http://localhost:8000/api/rest-auth/login/',
data
)
commit('ADD_USER', response.data)
this.$router.push('/')
} catch (error) {
return console.log(error)
}
},
}
export const getters = {
loggedIn(state) {
return !!state.credential
},
}
Here is the login.vue code
<template>
<client-only>
<div class="container">
<v-card max-width="500" class="margin-auto">
<v-card-title>Sign up</v-card-title>
<v-card-text>
<v-form @submit.prevent="submitUser">
<v-text-field
v-model="data.username"
label="Username"
hide-details="auto"
append-icon="account_circle"
></v-text-field>
<v-text-field
v-model="data.password"
label="Password"
hide-details="auto"
type="password"
append-icon="visibility_off"
></v-text-field>
<v-card-actions>
<v-btn color="success" type="submit" class="mt-4" dark>
Signup
</v-btn>
</v-card-actions>
</v-form>
<p>
Don't have an account? <nuxt-link to="/signup">Register</nuxt-link>
</p>
</v-card-text>
</v-card>
</div>
</client-only>
</template>
<script>
export default {
data() {
return {
data: {
username: '',
password: '',
},
}
},
methods: {
submitUser() {
this.$store.dispatch('signup/addUserLogin', this.data)
},
},
}
</script>
<style lang="scss" scoped>
.margin-auto {
margin: 2rem auto;
}
</style>