Example. I have a user
Vuex data that I use like this in templates:
// Inside <template>
<button
v-if="!user.expiredInfo.isExpired"
</button>
// Inside <script>
data () {
return {
disable: this.user.expiredInfo.isExpired ? 'text-muted' : '',
}
}
I have an action that does this:
const state = {
user: {}
}
async logout ({ commit }) {
commit('SET_USER', {})
},
So there's an error when I logout:
TypeError: Cannot read property 'isExpired' of undefined
How to prevent this kind of problems?
You should set user
to null when there is no logged in user, instead of trying to circumvent such errors with an empty object. This means you'll always need to take into consideration the fact that the user may not actually be logged in at a certain point in the template where you would render some data from the (possibly nonexistent) user object.
You can do things like this to avoid this kind of error (depending on the logic you want):
<button v-if="user && !user.expiredInfo.isExpired"></button>
<button v-if="!user || !user.expiredInfo.isExpired"></button>
Or if you have a lot of logged-in-specific templates, something like this:
<template v-if="user">
<!-- It's safe to access properties of the user object anywhere in here -->
</template>
Never assume that this.user
will always be non-null (unless that is an invariant you have enforced).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With