2

How can I loop an Axios request to fill an array of objects?

I'm trying to create a web interface that consumes a Star Wars API called swapi. It can be accessed in this link: https://swapi.co/

I can search for people, starships, planets, species and films. So, for instance, if I want to search for Luke Skywalker, I add /api/people/1/ like https://swapi.co/api/people/1/ .

So far so good.

Now, if I want every Star Wars characters, I simply remove the number 1, the url will be https://swapi.co/api/people/ and I will have the first ten characters out of 87, I think.

But I don't want 10. I want all of them... That makes me do a multiple request to grab all characters data. The problem is, if I use a loop to make the requests, let's say a while loop, it finishes all the search before the very first request brings the data to my code to treat it.

I'm using a global state through Redux and I'm calling Redux Thunk via componentDidMount(). It works fine, actually and the first ten characters data are retrieved and they fill my render method in React. But how can I make multiple requests without having a loop that ends up before those requests?

2
  • You might want to google "sync vs async in javascript" for this. There are many wonderful articles on this topic. Commented Jun 11, 2019 at 21:14
  • the term you're looking for is "pagination" Commented Jun 12, 2019 at 4:47

1 Answer 1

7

This is my solution if I got your question right using async / await:

getCharacter = async i => {
  let { characters } = this.state;
  let res = await axios.get(`https://swapi.co/api/people/${i}/`);
  characters.push(res);
  this.setState({ characters });
  return res;
};

componentDidMount() {
  // ids = [1, 2, 3, ..., 10]
  let ids = Array.from({length: 10}, (v, k) => k+1)
  Promise.all(ids.map(id => this.getCharacter(id)))
}

here's the complete code in codesandbox: https://codesandbox.io/embed/axios-react-ojpew?fontsize=14

Sign up to request clarification or add additional context in comments.

5 Comments

Hello Vahid Al, I opened the codesandbox link and the result were 10 names. Is it possible to load all 87 characters? After all my attempts, I'm still getting just 10 names as well.
of course, just change ids length from 10 to 87. I changed the codesandbox as well.
let ids = Array.from({length: 87}, (v, k) => k+1)
Sorry, I didn't realize I could change the length. That is the solution. And I didn't know the async / await so far. Thanks a lot.
you're welcome, maybe you want to check this out: javascript.info/async-await

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.