0

In a React application, I'm trying to setState in my App only after I get lots of AJAX fetches resolved to avoid multiple useless re-rendering.

I have something like this so far:

const URL = https://url/api/
const NUM_OF_ITEMS = 10;
let allData = [];

componentDidMount() {
  for (let i = 1; i <= NUM_OF_ITEMS; i++) {
    this.fetchData(`${URL}${i}/`)  //ex. https://url/api/1/, https://url/api/2/...
  }
}

const fetchData = URI => {
  fetch(URI)
  .then(response => response.json())
  .then(data => {
    allData = [ ...allData, data];
  })
  .catch( error => this.setState({ error });
}

Now I wanted to have just one single setState after all fetches are all resolved, and then save it all into localStorage:

this.setState({ allData })
localStorage.setItem("allData", JSON.stringify(allData))

Any ideas on how to do it?

1 Answer 1

3

You want to use Promise.all:

componentDidMount() {
  const requests = [];
  for (let i = 1; i <= NUM_OF_ITEMS; i++) {
    requests.push(this.fetchData(`${URL}${i}/`));
  }
  Promise.all(requests).then((arrayWithData) => {
     // here you can use setState with all the stuff
  });
}

const fetchData = URI => {
  fetch(URI)
  .then(response => response.json())
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer. But I guess something isn't working... I've placed console.logs of "requests" before and after Promise.all and they all return "undefined" :/
You must return the promise inside the fetchData: fetchData = URI => { return ....
If I make the fetch inside the push requests.push(fetch(${URL}${i}/).then(res => res.json())); it works fine, but if I try to do the fetches through a callback as in the example, it always returns "undefined". I wonder why this happen?!
The return!! Brilliant!! That's what I was missing!! Thanks a lot @moonwave99 and @ha-ja!!

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.