Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the undefined errors in Vue projects when you empty Vuex objects?

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?

like image 871
alex Avatar asked Oct 17 '22 09:10

alex


1 Answers

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).

like image 145
Decade Moon Avatar answered Oct 21 '22 05:10

Decade Moon