0

There is a form which submits some data to an API in my component. Assume that it's method is ProcessLogin(). Inside this function I have written my API calls using axios. With the help of then() I have handled my server response and displayed my toast. All good.

Now as a part of my code clean up, I have decided to move all my axios functions to another api.js file and export functions from there. Here is an example function I have in my api.js file :

function ApiLogin(data) {
const url   = `${BASE_URL}/authenticate`;
axios.post(url,data).then(response => {
  return response;
}).catch(error => {
  return error.response;
});
}

On the other side in my component I have my method defined as below :

methods: {
    ProcessLogin() {
    var status = ApiLogin(this.data);
    console.log(status);
 }
}

When executing this, I get undefined on my console. I know why it is happening. Because console.log(status) executes before ApiLogin could process and sends it's response. How to handle this kind of situation.? I know that callback is the rescue here, but I am not really sure about how to integrate it.

1 Answer 1

2

If you return the axios call from your ApiLogin function:

function ApiLogin(data) {
  const url = `${BASE_URL}/authenticate`
  return axios.post(url, data)
}

You could then handle the response in your component using then and console log from there:

methods: {
  ProcessLogin() {
    ApiLogin(this.data)
      .then(res => console.log(res))
      .catch(err => console.log(err))
  }
}

...or with async/await:

methods: {
  ProcessLogin: async function() {
    try {
      var status = await ApiLogin(this.data)
      console.log(status)
    }
    catch(err) {
      console.log(err)
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Thank you.
No problem. Glad this helped you out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.