Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I fetch all 19 pages of my API instead of just the first within the code I already wrote?

Only the first page of my api is fetched in my current code, and i know i should loop it over the amount of pages to fetch all the data from every page seperately, but I have no idea how to integrate it into the code I have currently. I’m very scared of ruining the code i already wrote, so if anyone knows an easy way to meld this into my current code, that would help a lot! thanks!!!

this is what i have now:

import Bird from "./Bird.js";

let map;
let layer;
let point;
let birdList = [];
let filteredBirdList = [];
let clickTimeout = null;
const clickDelay = 300;

function init() {
    fetch(`https://xeno-canto.org/api/2/recordings?query=cnt:belgium`)
        .then(function (response) {
            return response.json();
        })
        .then(function (json) {
            //console.log(json.recordings);
            json.recordings.forEach(function (recording) {
                const bird = new Bird(recording.date, recording.lat, recording.lng, recording.en, recording.file);
                //console.log(birdInstance);
                birdList.push(bird);
                //console.log(birdList);
                render(bird.HTMLstring);
            });
        })
        .then(function () {
            sorting();
            searching();
        });

    map = new maptalks.Map("map", {
        center: [4.400528, 50.499861],
        zoom: 8,
        baseLayer: new maptalks.TileLayer("base", {
            urlTemplate: "http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
            subdomains: ["a", "b", "c", "d"],
            attribution: '&copy; <a href="http://www.osm.org/copyright">OSM</a> contributors, ' + '&copy; <a href="https://carto.com/attributions">CARTO</a>',
        }),
    });

    layer = new maptalks.VectorLayer("vector").addTo(map);
}

//FUNCTIES VOOR SORTEREN/FILTEREN

function sorting() {
    const nameButton = document.getElementById("sortByName");
    const dateButton = document.getElementById("sortByDate");
    nameButton.addEventListener("click", function () {
        document.querySelector("#allBirds-list").innerHTML = "";
        birdList.sort(function (birdOne, birdTwo) {
            if (birdOne.name > birdTwo.name) {
                return 1;
            } else {
                return -1;
            }
        });
        birdList.forEach(function (bird) {
            render(bird.HTMLstring);
        });
    });

    dateButton.addEventListener("click", function () {
        document.querySelector("#allBirds-list").innerHTML = "";
        birdList.sort(function (birdOne, birdTwo) {
            if (birdOne.date > birdTwo.date) {
                return 1;
            } else {
                return -1;
            }
        });
        birdList.forEach(function (bird) {
            render(bird.HTMLstring);
        });
    });
}

function searching() {
    const field = document.getElementById("inputField");
    field.addEventListener("input", function (event) {
        const input = event.target.value;

        filteredBirdList = birdList.filter(function (bird) {
            if (input == bird.name) {
                return true;
            }
        });

        document.querySelector("#allBirds-list").innerHTML = "";

        filteredBirdList.forEach(function (bird) {
            render(bird.HTMLstring);
        });

        console.log(filteredBirdList);
    });
}

//FUNCTIES VOOR DE KAART

function addMarker(lat, lng, name) {
    console.log("pin");
    point = new maptalks.Marker([lng, lat], {
        visible: true,
        editable: true,
        cursor: "pointer",
        draggable: false,
        dragShadow: false, // display a shadow during dragging
        drawOnAxis: null, // force dragging stick on a axis, can be: x, y
        symbol: {
            textFaceName: "sans-serif",
            textName: name,
            textFill: "#34495e",
            textHorizontalAlignment: "right",
            textSize: 13,
        },
    });

    point.addTo(layer);
}

//FUNCTIES VOOR DE SELECTIE ACTIE

window.clicking = function (name, rec, lat, lng) {
    if (clickTimeout !== null) {
        clearTimeout(clickTimeout);
        clickTimeout = null;
        doubleClick(name, rec, lat, lng);
    } else {
        clickTimeout = setTimeout(() => {
            singleClick(rec);
            clickTimeout = null;
        }, clickDelay);
    }
};

function singleClick(rec) {
    console.log("enkel");
    playRecording(rec);
}

function doubleClick(name, rec, lat, lng) {
    console.log("dubbel");
    document.querySelector("#myGarden-list").innerHTML += `<button> ${name} </button> </br>`;
    playOnRepeat(rec);
    addMarker(lat, lng, name);
}

//FUNCTIES VOOR HET AFSPELEN VAN HET GELUID

window.playOnRepeat = function (audioFile) {
    const audio = new Audio(audioFile);
    audio.loop = true;
    audio.play();
};

window.playRecording = function (audioFile) {
    //console.log(audioFile);
    const audio = new Audio(audioFile);
    audio.play();
};

//FUNCTIES VOOR HET WEERGEVEN VAN DE KNOPPEN

function render(content) {
    document.querySelector("#allBirds-list").innerHTML += content;
}

init();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Promise.all to fetch several pages simultaneously:

async function fetchPages(length){
  return Promise.all(Array.from({length}, (_, i) => fetch(`https://xeno-canto.org/api/2/recordings?query=cnt:belgium&page=${i+1}`)
        .then(function (response) {
            return response.json();
        })));
 
}

async function init(){

  const pages = await fetchPages(3);
  for(const page of pages){
    console.log(Object.keys(page));
  }

}

init();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading