cristi _b
cristi _b

Reputation: 1813

Vue and data from REST API

While playing around with vue.js I noticed some strange behavior while trying to display on a page data from an API, but here's the strange thing :

Is it normal, or?

Source code :

  template:
    '<div>'+
      'Form with id = {{id}}'+
      '<br/>'+
      'has title = {{item.details.Title}}'+
    '</div>',
  data: function(){
    return {
      id: '',
      item: {}
    }
  },
  created: function() {
    this.get()
  },  
  methods: {
    get: function() {
      var self = this
      id = window.location.hash
      id = id.replace('#/whatever/','')
      axiosInstance.get('/thebackendresource/'+id) // <--- make http calls etc
        .then(function (response) {
          self.id = id
          self.item = response.data
          console.log(self.item)
        }).catch(function (error) {
          console.log(error)
        }
      );
    }
  } 

This is the case when vue 2.0.0 is used

Upvotes: 0

Views: 2736

Answers (1)

Saurabh
Saurabh

Reputation: 73669

You are getting this error, because when you are fetching data from axiosinstance, that time item.details is null, and when it tries to render it throws this error.

Once the api call is completed, it updates the the DOM and in turn re-renders the DOM, so you can see item.details.Title rendered.

You need to add a null check to prevent this error, which can be easily done using v-if, like follwoing:

template:
'<div>'+
  'Form with id = {{id}}'+
  '<br/>'+
  '<span v-if="item.details"> has title = {{item.details.Title}}'+
  '</span>' +
'</div>',

Upvotes: 2

Related Questions