Axios complete event

Viewed 2265

I'm using Axios for API services and just curious if there's any official way to handle a "complete" event as we have used in Ajax call.

So like

axios.get('/v1/api_endpoint?parameters')
  .then((res) => { .. })
  .catch((err) => { .. })
  .complete(() => {})     //  <== is there any way to handle this complete event? 
2 Answers

Following the axios documentation here, the secondary .then() is the one that I'm looking for.

Here's a good example of how to handle that axios complete event which will always be executed whether it has succeeded or failed.

axios.get('/v1/api_endpoint?with_parameters')
  .then((res) => { // handle success })
  .catch((err) => { // handle error })
  .then(() => { // always executed })        <-- this is the one

If you have to check whether an API call is a success or not, then you can use below code:

const response = await axios.post(
      "http://localhost:8000/xyz",
      { token, user }
    );
    const status = response.status
    if (status == 200) {
      console.log('Success')
      toast("Successful Transaction", { type: "success" });
    } else {
      console.log('Falure')
      toast("Falure", { type: "error" });
    }

You can also use finally to check if the event is completed or not. Attaching the link for your reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

Related