Home > Software design >  Promise All causes Infinite Loop
Promise All causes Infinite Loop

Time:07-21

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>

CodePudding user response:

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

  • Related