Bill
Bill

Reputation: 1477

Build an array from an API loop using Vue and AXIOS

I have a NIH API that can call only 50 pages at a time. The code below works for the first page of 50 items.

loadNIH() {
      let offset = 0;
      axios({
        method: "GET",
        url:
          "https://api.federalreporter.nih.gov/v1/projects/search?query=orgName:Medical University of South Carolina$fy:2016$&offset=" + offset +"&limit=50"
      })
        .then(res => {
          this.NIHData = res.data.items;
        })
        .catch(function(error) {
          console.log(error);
        });
    },

I need to loop all of the pages until I get all of the data. Each time the offset needs to increase by the number of pages received (requested 50) 9 pages in this call. I need it to ADD data to the array of this.NIHData. I got one working so I need some help creating the loop.

Thanks in advance

Upvotes: 0

Views: 447

Answers (1)

IVO GELOV
IVO GELOV

Reputation: 14269

You should repeatedly call the API until you get an empty resultset. This can be most easily achieved with the help of setTimeout()

loadNIH() {
  let params =
  {
    offset: 0
  }
  this.NIHData = [];
  this.fetchPages(params);
},
fetchPages(args)
{
  axios.get("https://api.federalreporter.nih.gov/v1/projects/search?query=orgName:Medical University of South Carolina$fy:2016$&offset=" + args.offset +"&limit=50"
  )
    .then(res => {
      this.NIHData.push(res.data.items);
      args.offset += res.data.items.length;
      if (res.data.items.length > 0) setTimeout(this.fetchPages, 2);
    })
    .catch(function(error) {
      console.log(error);
    });
}

Upvotes: 1

Related Questions