david
david

Reputation: 6785

How to identify when fetch is completed in vue.js

So I am making an api call in my created() hook, but there are a few things in my app I want to trigger AFTER the api call is finished, but I'm not sure how to do that. On average my API call takes about 5 seconds to return a huge chunk of json (terrible i know). In the example below, the logging statement prints well before the api call has finished.

snippet from component:

<script>
  created() {
    this.myEndpoint = 'testserver.com'
    fetch(this.myEndpoint)
    .then(response => response.json())
    .then(body => {
      for(let i=0; i<body.length; i++){
        this.job_execs.push({
          'version': body[i].version,
          'platform': body[i].platform.name,

        })
      }
    })
    .then(console.log('print AFTER the api call is completed'))
    .catch( err => {
      console.log('Error Fetching:', this.myEndpoint, err);
      return { 'failure': this.myEndpoint, 'reason': err };
    })
  },
};
</script>

I have tried moving the console.log statement to the mounted() hook, but this did not work either.

I believe I could achieve what I want using:

  $(window).on('load', function(){
    console.log('this logs after the entire page loads')
    });

But I'm sure there is a more elegant vue.js solution.

How do I identify in vue.js when the api call in my example has completed

Upvotes: 0

Views: 1738

Answers (2)

rh16
rh16

Reputation: 1073

Your code is fine in concept. The problem is

.then(console.log('print AFTER the api call is completed'))

Even though promise.then calls register async handlers, the calls themselves are evaluated synchronously, they are just supposed to take async callback functions as arguments. When you call

.then(console.log('print AFTER the api call is completed'))

console.log('print AFTER the api call is completed') is evaluated synchronously (logging out your message) and its return value (undefined) is then passed to .then as the callback.

Pass in a function here instead and you should see your log come at the appropriate time:

.then(() => console.log('print AFTER the api call is completed'))

Upvotes: 1

Get Off My Lawn
Get Off My Lawn

Reputation: 36299

You need to pass a function to the then statement. What you have will execute the console.log and pass its result to the then statement (which is undefined/void).

created() {
  this.myEndpoint = 'testserver.com'
  fetch(this.myEndpoint)
    .then(response => response.json())
    .then(body => {
      for (let i = 0; i < body.length; i++) {
        this.job_execs.push({
          'version': body[i].version,
          'platform': body[i].platform.name
        })
      }
    })
    .then(() => console.log('print AFTER the api call is completed'))
    .catch(err => {
      console.log('Error Fetching:', this.myEndpoint, err);
      return {
        'failure': this.myEndpoint,
        'reason': err
      };
    })
}

Upvotes: 0

Related Questions