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

Promise All causes Infinite Loop

I am trying to fetch an array of urls and using Promise.all for this. That works properly. However I need to show the data in UI and thus I am using useState hook. But setState ( setLocationResidents(results) ) causes an infinite loop. How can I fix this ?

Below is my code

const residentsUrl = [
'https://rickandmortyapi.com/api/character/10', 'https://rickandmortyapi.com/api/character/81', 'https://rickandmortyapi.com/api/character/208', 'https://rickandmortyapi.com/api/character/226', 'https://rickandmortyapi.com/api/character/340', 'https://rickandmortyapi.com/api/character/362', 'https://rickandmortyapi.com/api/character/375', 'https://rickandmortyapi.com/api/character/382', 'https://rickandmortyapi.com/api/character/395'
]

const [locationResidents, setLocationResidents] = useState([])

useEffect(() => {
  async function fetchAll() {
    const results = await Promise.all(
      residentsUrl?.map((url) => fetch(url).then((r) => r.json()))
    );
    console.log("results", results);
    setLocationResidents(results);
  }
  fetchAll();
}, [residentsUrl, locationResidents]);

 <div>
      {locationResidents
        ?.map((location) => (
          <div>{location.name}</div>
        ))}
 </div>

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 :

Remove locationResidents from useEffect watchers. It’s causing useEffect to re-run every time locationResidents changes.

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