I'm trying to make a login form with Vue 3, but I have difficoulties with getting a state in 'realtime' or computed. So when I try to login user from template it look like this.
<button class="login-button" type="button" @click="$store.dispatch('login', {email, password})">
Sign In
</button>
And this button is working fine, it's sending data and making request to backend with vuex like so:
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)
)
)
}
},
As you see in actions, it's setting user data in localStorage, so in state, I defined user like:
state: {
user: localStorage.getItem('user'),
},
And it will set everything, untill now. So now, when I try in navigation to get this state, it will not update it without refreshing a page. And I'm getting it like:
computed: {
token() {
return this.$store.state.user.user
}
},
Why should I refresh a page with this code? What am I doing wrong?
You are trying to set non-vue object.
app.mixin({
data() {
return {
localStorage: {
get(prop) {
return this[prop]
},
set(prop, val) {
window.localStorage.setItem(prop, val)
return this[prop] = val
}
}
}
},
created() {
window.localStorage.__proto__.get = prop => this.localStorage.get(prop)
window.localStorage.__proto__.set = (prop, val) => this.localStorage.set(prop, val)
window.localStorage.__proto__.get.apply(this)
window.localStorage.__proto__.set.apply(this)
}
})
localStorage.get('propName')
localStorage.set('propName', 'value')
state: {
get user() {
return localStorage.get('user')
}
}