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

Creating a POST request in Rails 3

Is there a way to integrate web services in Rails 3 by sending POST parameters to an external URL? Typically, I utilize a command line method like the one below for posting: curl -X POST -u "v10REVkw:XuCqIhyCw" \ -H "Content-Type: application/json" & ...

I'm facing issues with Webpack not being able to resolve and locate the node

Encountering difficulties while setting up and running the Three.js library as a module based on the guidelines provided in the manual at Here is a summary of the steps taken: Created package.json npm init Installed webpack npm i --save-dev webpack we ...

Utilizing Datatables with mysqli for server-side processing through JSON

I'm encountering an issue with my implementation of datatables. Certain pages are crashing due to the large amount of data being fetched from the database. I attempted to resolve this by utilizing server-side processing. Despite following the examples ...

Preview your uploaded image before finalizing

I am currently working on implementing a new upload feature for users of our forum. This feature will allow them to upload a personal picture. Here is what I have developed so far: HTML <label>Profile image</label> <div class="phot ...

Interact with a modal element using puppeteer

I'm having trouble clicking on the email login button inside a modal using Puppeteer for automation. The code is not able to find the modal element. Can someone assist me in debugging this issue? const puppeteer = require('puppeteer'); ( ...

What is the most effective way to ensure that a child component only executes when a link is clicked on the Vue component?

There are two components in my code The first component, which is the parent component, looks like this : <template> <ul class="list-group"> <li v-for="item in invoices" class="list-group-item"> <div class="ro ...

Searching for JSON array fields in a PostgreSQL database using Rails

Struggling to define a rational scope for my problem. I am trying to extract a list of Model objects with a specific "type" field within a json array column using postgresql. If anyone can guide me in the right direction, that would be helpful. I am open ...

What's causing the unexpected rendering outcome in Three.js?

Here is a mesh created in Blender: https://i.sstatic.net/KBGM5.jpg Upon loading it into Three.js, I am seeing this result: https://i.sstatic.net/PCNQ8.jpg I have exported it to .obj format and ensured all faces are triangulated. I am not sure why this is ...

Leverage angular-translate to establish placeholder text upon blurring

Just starting out with Angular and facing the challenge of implementing localization in my project. I have a lot of input fields that need their placeholders translated. In my HTML, I'm trying to achieve this: <input type="email" placeholder="{{ & ...

When utilizing jQuery.Mockjax to simulate the JSON data, the Backbone.Collection.fetch() function consistently results in a 404 error

My setup is pretty straightforward: Main.js: (function($) { "use strict"; var Company = Backbone.Model.extend({ defaults: { title: "", description: "" }, initialize: function() { ...

Using jQuery AJAX to retrieve JSON data from a REST API

My node.js and express.js application hosts a REST API at http://localhost:3000/api/kfc, providing JSON data. The route function looks like this: router.get('/kfc', function(req, res, next) { var response= { "id":"123", "name":"name1", "drink": ...

What is the best way to incorporate async/await in a useEffect hook in a React Native application?

Upon executing useEffect, my objective is to retrieve the token from AsyncStorage, fetch the data value using the axios.post('/auth/me') endpoint, and trigger the KAKAOLOG_IN_REQUEST action through dispatch. After verifying that the data value i ...

React - 'classProperties' is not currently activated in this setting

Recently, I incorporated Truncate-react into my project. Subsequently, React prompted me to install @babel/plugin-proposal-class-properties, which I promptly added to the package.json file as follows: "babel": { "presets": ...

Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID beca ...

Error encountered while trying to display a Jbuilder JSON object in JSON format

Currently, I am in the process of developing a student tracking website using RoR. Within my model, I have written the following code to construct json: self.as_json json = Jbuilder.new do |j| j.courses student_courses do |course| j.(course, : ...

"Error 404: Invalid request encountered while using React and

I am encountering an issue with a 404 not found error when I attempt to send a post request in React. My code involves using Django Rest Framework on the backend and React Axios on the frontend, but I am facing errors while making the post request. Below i ...

What is the best way to generate automatic suggestions based on the data received from a JSON API?

One option for retrieving autocomplete suggestions is by utilizing the Amazon API: http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=facebook The response from this query will include: ["facebook" ...

retrieving JSON data using ajax and processing it in PHP

I have some data that needs to be sent to the backend, and it looks like this: function view(){ let id = "12345678"; let profile = [{name:"dave", department : "Engineering"}, {name:"Tedd", ...

Sending data as a string in an AJAX request

I have been struggling with this coffeescript function that controls dynamic select boxes. I am trying to pass the content of "modelsSelect" to another script, but for some reason, it's not working as intended. customScript.coffee dynamicSelection = ...

I must conceal a single line of code or password within my Google Sheets script

I have developed a Google Sheet that is capable of receiving user input and then automatically populating the spreadsheet by accessing an external website. However, I am facing a dilemma as I would like to share the Google Sheet with others for their use, ...