Search code examples
javascriptvue.jsvue-resourcevue-component

How to return value in VueJS Mixin


I'm currently developing a webapp in Vuejs. I created a Mixin that I can access globally which handles any request to my api:

export default {

  data() {
    return {
      apiURL: 'http://example.com/api',
      timeout: 10000,
    };
  },

  methods: {

    callAPI(method, url, body) {
      this.$http({
        url: this.apiURL + url,
        method,
        body,
        timeout: this.timeout,
      })
      .then((response) =>
        response,
      (response) => {
        if (response.data.error) {
            this.error = response.data.error;
        } else {
          this.error = 'We can\'t connect to the server. Please try again in a few minutes.';
        }
        return response;
      });
      // return 'test';
    },

  },

};

Now, in some of my components I call the api function:

const api_response = this.callAPI('POST', '/auth', credentials);
alert (api_response);

It works fine, but one thing doesn't work as expected. I expect my api_response constant to have the value of response but it is always undefined. So every time I got this alert with undefined. How is that possible? When I uncomment the return 'test' line it works: I got an alert with test, but it doesn't seem to work within the this.$http part...


Solution

  • Your callAPI has no return statement, so it returns undefined. If it returned your $http call, it still would not give you response, but would be a Promise, so you would want to do something like

    let api_response;
    this.callAPI('POST', '/auth', credentials).then((response) => api_response = response);