Amit Erandole Amit Erandole - 9 days ago 5
Ajax Question

Vue 2.1 calling method in beforeCreate hook is not working

I am making an async call to some local

json
data before my component is created. So this code actually works fine:

beforeCreate : function() {
var self = this;
fetch('/assets/data/radfaces.json')
.then(function(response) { return response.json()
.then( function(data) { self.users = data; } );
})
.catch(function(error) {
console.log(error);
});
},


Now I just want to refactor and move this to a separate method:

beforeCreate : function() {
this.fetchUsers();
},

methods: {
fetchUsers: function() {
var self = this;
fetch('/assets/data/radfaces.json')
.then(function(response) { return response.json()
.then( function(data) { self.users = data; } );
})
.catch(function(error) {
console.log(error);
});
}
}


And now everything stops working. I get an error:
app.js:13 Uncaught TypeError: this.fetchUsers is not a function(…)


Why can't I access the
fetchUsers
method in the
beforeCreate
hook? What is the work around?

Answer

It's because methods hasn't been initialized yet. The easiest way around this it to use the created hook instead:

  created : function() {
    this.fetchUsers();
  },

  methods: {
    fetchUsers: function() {
      var self = this;
      fetch('/assets/data/radfaces.json')
        .then(function(response) { return response.json()
        .then( function(data) { self.users = data; } );
      })
        .catch(function(error) {
        console.log(error);
      });
    }
  }