I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get the next one. However, my goal is to receive all entries at once.

   let next_url = "/hustengium" 
    let uri = "http://fasttrack.herokuapp.com/"  
    let h = new Headers()
        h.append('Accept', 'application/json')

    let req = new Request(uri + next_url, {
        method: 'GET',
        headers: h,
        mode: 'cors'

    })  

   fetch(req )
    .then(response => response.json() )
    .then(data => {
        let str = JSON.stringify(data) 
        document.querySelector("div#output").textContent = str
    
     console.log(data["next"] )
    })

    .catch(err => {
        let nm = err.name
        let msg = err.message
        alert(`CATCH: ${nm} ${msg}`)
    })

Answer №1

Just as with a set of Russian nesting dolls, you can't access them all at once. Each one must be opened individually to reveal the next:

(function loop(root, path) {
  const proxy = 'http://cors-everywhere.herokuapp.com/';
  fetch(proxy + root + path, { headers: { Accept: 'application/json' }})
    .then(res => res.json())
    .then(res => {
      console.log(JSON.stringify(res));
      if (res.next) loop(root, res.next);
    })
    .catch(console.log);
})('http://fasttrack.herokuapp.com', '/');

Answer №2

I finally found the solution to my problem. It turned out that the issue was caused by not making my URL and path dynamic, which resulted in the same URL being called repeatedly.


  fetch(`${dynamicUrl}${dynamicPath}` )
    .then(response => response.json() )
    .then(data => {
           section.innerHtml = data.next
         if(data.next) {
           loop(data.next)
}
       
    })

loop()

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

I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code: try { const res = await fetch("/api/email-registration", { method: "POST", headers: { ...

Issue with AngularJS UI Router not loading the inline template and controller

I am trying out UI Router for the first time in my AngularJS project. I am facing an issue where, when I click on a link to view a post, it doesn't display. The post template is not visible and I remain on the home page. The URL flashes as http://loc ...

Ways to extract an object from JSON into PHP

Can someone help me figure out how to extract an image link from this API ()? The API endpoint is https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&format=json&piprop=original&titles=Minecraft&pilicense=any. I've tri ...

Differences between the http module and Express framework

After noticing this common pattern, I've become intrigued : const server = http.createServer(app); // Listen on provided port, on all network interfaces. server.listen(port); server.on('error', onError); server.on('listening', on ...

Eliminate the use of backslashes in JSON responses when using the WordPress REST API

As I work on extending the Wordpress Rest API, I encounter backslashes even after adding json flags to eliminate them. Below is what I am attempting: stripslashes(json_encode(['success'=> true], JSON_FORCE_OBJECT | JSON_HEX_APOS)); The outpu ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...

Trouble with React Material Select Options Failing to Populate

After iterating and producing MenuItems, I am able to see the items when I console.log, but in the UI, the dropdown appears empty. I'm puzzled as to why the Select's are not being populated. Any thoughts on this issue? Below is the supplied code ...

Is it possible for the NextJS Client component to only receive props after rendering props.children?

Encountering a puzzling issue that has me stumped... In my setup, I have a server side component that fetches data and then sends it over to the client component, which is all pretty standard. Here's where things get weird... When I log the data on ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

Pending activation of the Timer Fired event

Below is some code I have for implementing swipe gesture functionality: this.topSlide = this.elementRef.nativeElement.querySelector('.product_rate_slide'); if (this.topSlide) { this.topSlide.addEventListener('touchstart', this.hand ...

Utilizing the ref received from the Composition API within the Options API

My current approach involves utilizing a setup() method to bring in an external component that exclusively supports the Options API. Once I have imported this component, I need to set it up using the Options API data. The challenge I face is accessing the ...

Express route fails to wait for Redis server response before moving on

How can I modify the code below to ensure that the res.json(...) command is not executed until all open calls to the Redis client.somecommand(..) have completed successfully? An issue occurs in the code where the client.hmset(uname, { ... } attempt to set ...

What is the best way to insert values into a JSONObject in Java?

After including data with json.put("key", "value"), the output turned out to be {"key": "value"}. Desiring a result in the format of {key: "value"} Is there a way to achieve this? ...

Unable to locate additional elements following javascript append utilizing Chrome WebDriver

I have a simple HTML code generated from a C# dotnet core ASP application. I am working on a webdriver test to count the number of input boxes inside the colorList div. Initially, the count is two which is correct, but when I click the button labeled "+", ...

Querying with HiveQL: A guide on selecting and filtering records using nested JSON array values

Our logging database stores custom UI data in serialized JSON format. I have been using the lateral view json_tuple() function to navigate through the JSON object and extract nested values. However, I now need to filter my query results based on whether an ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Is it necessary to include a back button when navigating through paginated tables?

Within my AngularJS application, I have implemented pagination on the user list page. This allows me to retrieve ten users at a time from the server, with each click loading another set of ten users on a new page. The user details are presented in a tabl ...

Event listeners can only be removed within the useEffect hook

I have encountered an issue when trying to remove an event listener added inside the useEffect hook. The listener is set up to run once after the first rerender, thanks to the empty array passed as the second argument in the useEffect call. I attempted t ...

showing a pop-up message when a specific javascript function is triggered

Here is a unique code snippet showcasing a customized dialog box created with HTML, CSS, and JavaScript. The dialog box is displayed when a button is clicked. <!DOCTYPE html> <html> <head> <style> /* Custom Modal Styles */ .modal { ...