[Vuejs]-State variable triggers error when displaying it in template as it's temporarily null when component mounts

1👍

In your mapped getter you could default to an empty object like

state => state.dashboard.user || {}

That way things like user.first_name would be undefined rather than attempting to look for a property on the value null

0👍

Ok. I’ve rewritten the code.

store.js

state: {
  user: ''
},
mutations: {
  SET_USER: (state, user) => {
    state.user = user
  }
},
actions: {
  getUser: (context, user) => {
    axios.get('url/to/server')
         .then(res => {
            context.commit('SET_USER', res.data)
         })
         .catch(error => {
            console.log(error)
         })
  }
}

Now in your root component (App.vue for example)

import {mapActions} from 'vuex'
export default{
  ...
  mounted() {
    this.getUser()
  },
  methods: {
    ...mapActions(['getUser'])
  }
}

In the component, you wish to use the user data

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

import {mapState} from 'vuex'
export default{
  computed: {
    ...mapState(['user'])
  }
}

This will work.
Hope it helps.

Leave a comment