Home > Net >  Show an info only if it exists with $auth and vuejs (nuxt)
Show an info only if it exists with $auth and vuejs (nuxt)

Time:10-26

I want to show a data to the user only if it exists (so if he identify) but i go an error : Cannot read properties of undefined (reading 'email') I do not understand because i've used the v-if property to avoid that error here

<template>
  <div>   
     <Navbar/>
     <p v-if="this.$auth.$storage.state.user.email"> {{ this.$auth.$storage.state.user.email }} </p>
  </div>
</template>

CodePudding user response:

The variable this.$auth.$storage.state.user is null.

Such as the v-if is on the email object or user, it throw error before checking the variable.

So, I suggest you to use this code:

<template>
  <div>
     <p v-if="this.$auth.$storage.state.user">{{ this.$auth.$storage.state.user.email }}</p>
  </div>
</template>

CodePudding user response:

Actually If you consider the test cases, it will be like this.$auth will be valid one but it might not contain $storage so it might throw an error saying Cannot read state of undefined. The same can be applicable when you go deeper checking for attributes. So to do this kind of check at each stage you can follow the below approach

<template>
  <div>
     <p v-if="$auth?.$storage?.state?.user">{{ $auth.$storage.state.user.email }}</p>
  </div>
</template>

For optional chaining to work inside v-if, install @babel/plugin-proposal-optional-chaining and add it to to your babel’s config plugins as @babel/plugin-proposal-optional-chaining

CodePudding user response:

A simple solution that can work out of the box would be

<template>
  <div>
    <Navbar />
    <p v-if="isEmailFilled">
      {{ $auth.$storage.state.user.email }}
    </p>
  </div>
</template>

<script>
export default {
  computed: {
    isEmailFilled() {
      return this.$auth?.$storage?.state?.user?.email
    },
  },
}
</script>
  • Related