What is the best method for retrieving data from multiple API pages using axios?

Can someone help me troubleshoot this issue? I'm trying to retrieve data from all pages in an API. However, after adding the while loop, my code stopped working. What is the correct way to implement a page loop in this scenario?

    getCustomers: function() {
        let url = '/crm/customer/';
        return axios.get(url).then((response) => {
           this.customers = response.data.results;
           if (this.customers.length === 100) {
                let i = 2;
                axios.get('/crm/customer/?page=' + i).then((response) => {
                  this.c = response.data.results;
                  i += 1;
                  for (let item of this.c.values()) {
                      this.customers.push(item);
                  }
                  while (this.c.length === 100) {
                      axios.get('/crm/customer/?page=' + i).then((response) => {
                        this.c = response.data.results;
                        i += 1;
                        for (let item of this.c.values()) {
                          this.customers.push(item);
                        }
                      }).catch( error => {}).finally(() => (global_waiting_stop()));
                  }
                }).catch( error => {}).finally(() => (global_waiting_stop()));
           }
         }).catch( error => {}).finally(() => (global_waiting_stop()));
    },

Answer №1

If I were to approach this, I would begin by creating an asynchronous function named getPageOfResults:

async function getPageOfResults(page) {
    const response = await axios.get('/crm/customer/?page=' + page);
    return response.data.results; // .results.values()? I'm not sure
}

Following that, within another async function, I would implement a loop to achieve the desired outcome:

async function getAllResults() {
    const customers = [];
    let lastResultsLength = 100;
    let page = 1;
    while (lastResultsLength === 100) {
        const newResults = await getPageOfResults(page);
        page++;
        lastResultsLength = newResults.length;
        customers = customers.concat(newResults);
    }
    return customers;
}

This setup involves monitoring the current page number using a variable and continuously fetching new pages until less than 100 results are returned.

The concat function is used to combine all results into a single list before eventually returning it in its entirety.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The technique for converting a JSON format date string into a date format

Currently, I am fetching data from a database using AJAX and displaying it in HTML text boxes for updating purposes. Below is the Web Method code that successfully retrieves the data: [WebMethod] public static List<Employee> getEmployee() { var ...

Error encountered when deploying VueJS to production: DOMException stating "The action cannot be completed due to security concerns."

I recently deployed my VueJS application on Netlify. While the app functions perfectly on my local machine, there seems to be an issue with the production deployment in Firefox. When attempting to 'connect', the browser throws the following error ...

Node.js returns a 404 Not Found error when trying to access localhost

After creating a basic login system using Node.js and Express 4.x, I encountered an issue where accessing localhost:3000 resulted in a "Not Found 404" error. Upon investigation, I realized that the problem stemmed from discrepancies between code written fo ...

What is the process for decrypting the data that was encrypted using node-jose?

I am currently in the process of incorporating basic JOSE encryption and decryption functionalities by utilizing node-jose. This is my code implementation (using Node 8.2.1) const { JWE } = require('node-jose'); const jose = (publicKey, privat ...

Is there a reason why the Chrome browser doesn't trigger a popstate event when using the back

JavaScript: $(document).ready(function() { window.history.replaceState({some JSON}, "tittle", aHref); $(window).bind("popstate", function(){ alert("hello~"); }); }); Upon the initial loading of the www.example.com page, the above JavaScript code is ex ...

How can we determine if a v-for loop in Vue.js that includes a v-if condition has rendered any elements?

In the scenario where the code below is implemented: <template v-for="(item, index) in items" v-if="item.name === 'foo'"> <p>{{ item.name }}</p> </template> Is there a way to display a message if this loop doesn' ...

What is the best approach to implementing a blur function for a specific input within a parent component?

I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives: <app-input ...></app-input> My goal is to pass the blur event/function to the parent component speci ...

Incorporating Flash videos into an Angular HTML partial using AngularJS techniques

I've been struggling to embed a flash game in an angular HTML partial. The game loads without errors, but when I right click on the blank flash screen, it says "movie not loaded." I have tried using https://github.com/Pleasurazy/angularjs-media and an ...

What is the rationale behind Typescript permitting the assignment of an "any" object type to a class object?

Within my codebase, there is a class object that I have initialized: groupNameData: GroupNameData = new GroupNameData(); In addition, I also have an any object called groupNameDatas. groupNameDatas: any; Experiment 1 (class = any) To experiment with ...

Getting an `UnhandledPromiseRejectionWarning` notification despite already handling the rejected promise

I have created a function that loops through a Generator containing both synchronous code and Promises: module.exports = { isPromise (value) { return typeof value === 'object' && value !== null && 'then&apo ...

Ways to transfer variables between JavaScript files using a deferred function

I am encountering an issue while trying to retrieve a json object from another JS file. It appears to be a timing problem as the setTimeout function I added runs twice; first with the object correctly populated, and then again with the object becoming unde ...

Vue email validation is failing to return a valid email address

I'm relatively new to Vue and have implemented email validation using the reg expression in my Vue script data for this project. By utilizing console.log(this.reg.test(this.email)) and observing the output while users input their email, the validation ...

javascript game for reversing an array

in case(po==true){ snake_array.reverse(); var i=0; var c=snake_array[i]; //drawing the head draw_head(c.x,c.y); for(i=1;i<snake_array.length;i++){ //drawing the body var c=snake_arr ...

Angular.js text areaS galore

having trouble getting text from specific message <div class="feed-element"ng-repeat="message in messages"> <a href="" class="pull-left"> <img alt="image" class="img-circle ...

Disable the div by graying it out when the button is clicked

In my jsni form, I have implemented a click handler on the save button. When the save button is clicked, I would like the specific div to be greyed out to indicate that data is being saved. var x=$doc.createElement("div"); x.id="nn"; var lbl=$doc.createEl ...

An array in Vue.js containing a single object element

<div class='highlighted-item' v-for='(product, index) in products' :key='index'> <span> {{ product.title }} </span> {{ product.company.icon }} </div> I have an array called products which contains ...

The custom filter in AngularJS fails to activate when a click event occurs

I am trying to customize the filtering of my table data based on selected conditions from a dropdown menu. I have created an AngularJS custom filter and passed all the necessary parameters. The desired functionality is that if no conditions are selected, ...

What is the process for associating JSON reponses with button actions on a webpage?

I developed a JavaScript script that interacts with a Tableau server API to handle running jobs. The script presents the retrieved jobs on a web page, along with corresponding buttons that enable users to terminate specific jobs. While the script function ...

Database with individual queries in each row

I'm in search of a tutorial that can guide me on creating an effective table using AJAX. For instance, I have one table containing user information and another table with records for each user. Users Table UserID | Name =======|=========== 000001 | K ...

Strategies for re-rendering a React component when the useState value remains the same or retains its previous value

I am currently using a useState hook to store the value of selectFolderId: const [selectFolderId, useSelectFolderId] = React.useState(documentStore.id) Despite trying to update selectFolderId with the new value from DocumentStore by using a useEffect hook ...