R
R
Roman2021-02-20 07:32:49
Vue.js
Roman, 2021-02-20 07:32:49

How to call a custom function in Axios (in Vue) on success (see code)?

This is a simple example code, I'm trying to do it like this:

<button @click="get">Get API...

...

methods: {
    lg() {
      console.log("Log 1");
    },
    lgt() {
      console.log("Log 2");
    },
    get() {
      this.axios
        .get("https://api.coindesk.com/v1/bpi/currentprice.json")
        .then(function(response) {
          console.log(response);
          this.lg();
        });
    },
  }


But it says to me:

Uncaught (in promise) TypeError: Cannot read property 'lg' of undefined at eval


What are the ways to solve this problem?

I need other functions defined by me (in the example: lg () and lgt ()) to be launched in case of successful receipt of data, how to do this?

That is, it receives data through the API, but does not see my functions, and, accordingly, does not start.

Although for example this:

methods: {
    lg() {
      console.log("Log 1");
      this.lgt();
    },
    lgt() {
      console.log("Log 2");
    },


works as expected: it displays "Log 1" and "Log 2" in the console - and if it is in a promise, it does not see it ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
no_one_safe, 2021-02-20
@procode

You need to use arrow functions

get() {
      this.axios
        .get("https://api.coindesk.com/v1/bpi/currentprice.json")
        .then(response => {
          console.log(response);
          this.lg();
        });
    },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question