Traverse the successive API result pages interconnected via their respective URLs

Currently, I am attempting to iterate through all the pages of an API response that contains a URL linking to the next page:

const apiURL = 'https://wger.de/api/v2/exercise/?format=json&page=29';

    async function retrieveExercises() {
        const fetchResponse = await fetch(apiURL);
        const data = await fetchResponse.json();
        data.results.forEach(item => console.log(item.name));
    }
    retrieveExercises();

What approach would you take to achieve this?

Answer №1

To retrieve exercise data from an API, you can implement a solution using a while loop:

async function getExercises () {
  let url = 'https://wger.de/api/v2/exercise/?format=json'

  while (url) {
    const res = await fetch(url)
    const data = await res.json()

    for (const item of data.results) {
      console.log(item.name)
    }

    url = data.next
  }
}

// It's important to handle errors as well, to prevent unhandled rejections.
// Ensure this code is executed within an async function to catch any errors that may occur.
getExercises().catch(e => console.error('Failed to get exercises', e))

In addition, I found out that specifying a limit parameter works efficiently. By setting a higher limit like

https://wger.de/api/v2/exercise/?format=json&limit=1000
, it reduces the number of requests required. With only 685 results currently available, setting a limit of 1000 would retrieve all results in one request. Nonetheless, implementing the fetching logic is essential for future-proofing in case the dataset grows beyond the set limit.

Answer №2

To solve this problem, you can utilize recursion.

let currentPage = 1;
const limit = 5;
const apiURL = 'https://wger.de/api/v2/exercise?format=json';

const fetchExerciseData = async () => {

    const response = await fetch(`${apiURL}&page=${currentPage}`);
    const exerciseData = await response.json();

    // If there are results and the current page is within the limit
    if (exerciseData.results.length && currentPage <= limit) {
        currentPage++;
        exerciseData.results.forEach(item => console.log(item.name));
        fetchExerciseData();
    } else {
        return;
    }
}
fetchExerciseData();

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

What is the best way to skip certain steps within a Promise using Bluebird?

Here is an example of some code: Queues.findOne({_id: id}) .then(function(q) { var status = q.status; //... }).then(function(q) { // A }).then(function(q) { // B }).then(function(q) { // C }).then(function(q) { // D }).then(function(q) { // E }).then ...

Leveraging JSON in Java

I am a novice looking to create my own weather app that can retrieve information from the web and display it to users. However, I am facing challenges with passing user input to the JSON method specifically within the ActionListener section. Can anyone p ...

Sending Parsed Information to Callback for Flexible Use

Is there a way to pass the value of coins, or even better, currency to my callback function so I can freely use the parsed JSON data in other functions? function fetchJSON(path, callback) { var jsonReq = new XMLHttpRequest(); jsonReq.onreadystatechang ...

What is the process for transforming a block of plain text into a formatted text with multiple paragraphs while tracking the word count

I am faced with the task of transforming a simple text consisting of 5000 words into multiple paragraphs, each containing 1000 words. Is there a way to accomplish this? If so, I would greatly appreciate any guidance or assistance you can provide. ...

Creating identical class names for UL elements underneath LI using JavaScript

In my attempt to dynamically generate the class name within the ul element, I successfully achieved the expected result. The outcome can be viewed in the console of the snippet provided for reference. However, I'm facing a challenge when attempting t ...

Angular local storage not receiving API variable

In the process of developing a reservation system, I encounter an issue where the calculated price from Skyscanner API is not getting stored in localStorage along with other user inputs such as dates, cities, and number of passengers. Despite successfully ...

How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and ...

Is it better to use scale.set() or simply increase the size of the model in Three.js?

When it comes to scaling 3D models in Three.js (or any other 3D renderers), what is considered the best practice? Recently, I encountered a situation where I loaded a model only to realize that its size was too small. In order to adjust the size, I used m ...

The stringformat package in Node.js does not include a method for formatting strings

I tried installing the nodejs stringformat package and ran their first example from here. Unfortunately, a frustrating error popped up: > npm install stringformat > node > var $ = require('stringformat') > console.log($.format("Hell ...

Collect the text shown in an alert message created with JavaScript

I'm currently unsure if this is achievable or not. In one of my scenarios, I aim to extract text that appears in alert boxes on external websites by including my JavaScript file. Is there a method to obtain the text content shown in an alert message ...

Converting JsonObject data into a ListView

try{ JSONArray name =new JSONArray(); JSONObject data=json.getJSONObject("data"); JSONObject orders=data.getJSONObject("orders"); JSONObject country=orders.getJSONObject("US"); Log.d("JSON",name.t ...

Angular Directive: The power of one-way binding

Is there a simple way to implement one-way binding in an angular directive? I've been searching for an easy example, but haven't had much luck. The documentation isn't very clear either: & or &attr - allows you to execute an expre ...

Is it possible to craft a miniature duplicate of a div element?

My challenge is to create a smaller version of a dynamically generated div that contains text, photos, and more. The original div has a height:width ratio of around 10:1. I aim to replicate this div on the same page but at 1/8 of the width. UPDATE: All t ...

ReactJS: Component not updating after property change causing re-render failure

I've encountered a React problem and I'm having trouble pinpointing the issue. In the code snippet below, I've implemented an accordion component that should show or hide based on the value of a state variable called displayForm. The goal i ...

Is it possible to utilize a utility function to modify the state of useState during the

I have a small function for handling uploads that looks like this: const handleUploadPhoto = filename => { setHasImage('has-image'); setPostButtonState(''); onAddedPhoto(filename); setPostImageFilename(filename); }; I find m ...

What could be causing the function to not work properly within the React component?

Having trouble with a React component utilizing speech recognition for converting speech to text. Initialized the recognition functions within the component but encountering errors. Need assistance in troubleshooting this issue. const speechRecognition = w ...

Tips for serializing canonical/normalized JSON data using PHP

In PHP, the order of keys in JSON is not significant. The json_encode function will use the internal order of keys when converting to JSON format. It is important for me to ensure that identical JSON data is always serialized in the same way. Take for exam ...

Guide on adding values in sequence from an array to another in javascript and saving the result in a fresh array?

I am facing a challenge with two arrays: const initialAmount = [50] const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ] Is there a way to create a new array that adds each value from transactionAmounts to the ...

TypeScript does not verify keys within array objects

I am dealing with an issue where my TypeScript does not flag errors when I break an object in an array. The column object is being used for a Knex query. type Test = { id: string; startDate: string; percentDebitCard: number, } const column = { ...

Activate a modal component in ReactJS when a click event occurs

I'm having trouble integrating ReactStrap Modal into my NavBar and I haven't found a solution yet. I created a handler function to be triggered on a click event, but I can't figure out how to call my login component from this handler functio ...