Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  137] [ 3]  / answers: 1 / hits: 24095  / 7 Years ago, mon, october 23, 2017, 12:00:00

I have the following Navigation.vue component:



<template>
<div>
{{user.first_name}}
</div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
name: 'hello',
methods: {
...mapActions(['myAccount'])
},

mounted: function () {
if (localStorage.getItem('access_token')) {
this.myAccount()
}
},

computed: {
...mapGetters(['user'])
}
}
</script>


This code returns:



[Vue warn]: Error in render function: TypeError: Cannot read property 'first_name' of null


but the strange thing is that user first name is showing correctly. What am I doing wrong?


More From » vue.js

 Answers
9

You are most likely getting that error because user in your Vuex store is initially set to null. The user getter mapped to your Vue component is returning that null value before some initialization to the Vuex store properly sets the user.



You could initially set the user to an empty object {}. This way, user.first_name in your Vue component's template will be undefined and nothing will be rendered in the template.






Alternatively, you could add a v-if=user attribute to the containing div element:



<div v-if=user>
{{ user.first_name }}
</div>


This way, the div and its contents will not be rendered until the value of the mapped user property is truthy. This will prevent Vue from trying to access user.first_name until the user is properly set.


[#56144] Friday, October 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cadendericki

Total Points: 482
Total Questions: 109
Total Answers: 103

Location: Ecuador
Member since Thu, Jun 4, 2020
4 Years ago
cadendericki questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Wed, Jul 8, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;