Vue 2.1 calling method in beforeCreate hook is not working

Amit Erandole picture Amit Erandole · Nov 30, 2016 · Viewed 21.8k times · Source

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

craig_h picture craig_h · Nov 30, 2016

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);
      });
    }
  }