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

3

11

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?

Fording answered 23/10, 2017 at 20:15 Comment(2)
I'm assuming this is because, in your vuex store, the state of user is initialized as null. Just initialize the user to an empty object {}.Respecting
Add Your comment as an answer and I will accept it.Kilmer
R
27

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.

Respecting answered 23/10, 2017 at 20:42 Comment(0)
N
0

A solution that worked for me was to set the user to an empty string ' ' instead of null.

const state = {
    user: ''
}
Nannana answered 7/4, 2018 at 3:44 Comment(0)
M
-1
beforeMount(){
 if (localStorage.getItem('access_token')) {
        this.myAccount()
   }
}
Missend answered 5/1, 2021 at 23:53 Comment(1)
Welcome to Stack Overflow. Please write your answer in English, as Stack Overflow is an English only site.Communicable

© 2022 - 2024 — McMap. All rights reserved.