I'm currently facing a challenge while developing a login form using Vue 3. I am having difficulty in getting the state to update 'realtime' or computed. When attempting to login a user from the template, the code looks like this:
<button class="login-button" type="button" @click="$store.dispatch('login', {email, password})">
Sign In
</button>
The login button works perfectly fine, as it sends data and makes a request to the backend using Vuex with the following action:
actions: {
async login(commit: any, payload: any ) {
API.post('/login', {
email: payload.email,
password: payload.password
})
.then((response) => (
localStorage.setItem('user', response.data.token)
)
).catch((e) => (
console.log(e.message)
)
)
}
},
In the actions section above, the user data is stored in the localStorage. In my state declaration, I defined the user as follows:
state: {
user: localStorage.getItem('user'),
},
At this point, everything seems to be functioning correctly. However, when trying to access this state during navigation, it doesn't update without a page refresh. The attempt to retrieve the state is done through the following computed property:
computed: {
token() {
return this.$store.state.user.user
}
},
Why does the page need to be refreshed for this code to work? What could possibly be going wrong here?