Home > Software design >  How to get all the data with Promise.all in the useEffect hook?
How to get all the data with Promise.all in the useEffect hook?

Time:12-12

I have this useEffect hook, that is trying to fetch all the data in one time

  useEffect(() => {
    let promises = [];
    data.forEach(item => {
      promises.push(fetch(`https://app.subsocial.network/subid/api/v1/check/${(item.name).toLowerCase()}`))
    });

    Promise.all(promises)
      .then(response => response.map(item => item.json()))
      .then(data => console.log(data))
      .catch(error => console.log(error))
  }, [data]);

But, instead the data I have this in console:

enter image description here

CodePudding user response:

The json() method returns a promise.

This means that you've used Promise.all to wait for all the response promises to resolve, but then you just generate a new bunch of JSON parsing promises instead.

Generate the JSON parsing promises before you use Promise.all.

i.e.

promises.push(
    fetch(`https://app.subsocial.network/subid/api/v1/check/${(item.name).toLowerCase()}`))
    .then(response => response.json());

CodePudding user response:

You are almost there, you just need to analyze every promise that you get the first Promise.all

useEffect(() => {
  let promises = [];
  data.forEach((item) => {
    promises.push(
      fetch(
        `https://app.subsocial.network/subid/api/v1/check/${item.name.toLowerCase()}`
      )
    );
  });

  Promise.all(promises)
    .then((responses) => {
      // Take all responses and analyze them with another Promise.all
      return Promise.all(
        responses.map((response) => {
          return response.json();
        })
      );
    })
    .then((data) => {
      // Extracted data
      console.log(data);
    })
    .catch((error) => {
      // Catched errors
      console.log(error);
    });
}, [data]);

In then method you are getting all responses, and wrapping them with yet another Promise.all so that you can extract from them what they receive.

  • Related