Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - how to fetch all the 87 object in this api

I am trying to make a get request with axios to return all 87 objects in this api: https://swapi.py4e.com/api/people/

If we choose to show one object we modify the url like that "https://swapi.py4e.com/api/people/2" this returns the properties of the second object in the api so I thought if I try to make a simple for loop to fetch all 87 objects one by one:

const fetchPosts = async () => {
    setLoading(true);
    let n = 1;
    for (let i = 0; i < 88; i++) {
        n = n + i;
        const res = await axios.get('https://swapi.py4e.com/api/people/' + n);
        setPosts(res.data);
    }
    setLoading(false);
}

This code has weird behaviour of returning only 12 objects and when it stops it gives error that it actually stopped at 94th and that's not true because it actually returned only 12

the error: enter image description here

question from:https://stackoverflow.com/questions/65944874/how-to-fetch-all-the-87-object-in-this-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sending 87 requests to get 87 results from a paginated API is very inefficient.

You should also never hard-code "magic numbers" like 87 in your code, especially when interacting with an API you don't control. If people get added to or removed from the list, your code will no longer work correctly.

Note that /people/ provides a next field that gives you a link to the next page. You can therefore use an asynchronous while loop to get all the results in just 9 requests (10 results per page).

Something like the following — you can swap out native fetch for axios if required:

;(async () => {
    let nextPage = 'https://swapi.py4e.com/api/people/'

    let people = []

    while (nextPage) {
        const res = await fetch(nextPage)

        const { next, results } = await res.json()

        nextPage = next

        people = [...people, ...results]
    }

    console.log(people.length)
    console.log(people)
})()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...