How to set a state in React Native in a nested asynchronous for loop?

I want this code snippet to loop through an array of generic locations that includes cafe’s, bars, stores, etc. On each iteration I run it through a google places api that finds every location with that keyword passed in that’s open and for each result, I want it to add each result from the api to a state called placesOpen. So far it’s able to get the locations no problem but the state is not being updated.

 Geocoder.from(location).then((json) => {
        const locResult = json.results[0].geometry.location;;
        genericLocations.forEach(async (type) => {
          const response = await fetch(
            `google places url`
          );
          const data = await response.json();
          data["results"].forEach((result) => {
            setPlacesOpen(placesOpen => [result["name"],...placesOpen]);
          });
        });
      })

  • What makes you think state is not updated? Did you verify the data.results that you actually got back? Did the code run without errors?

    – 




  • Btw, don’t mix async/await with .then(…), and don’t use forEach for asynchronous code.

    – 

  • @Bergi I console logged it later on and it returns empty

    – 

  • 1

    Where exactly? What does “later on” mean? Did you actually log the old state due to a stale closure?

    – 

  • 1

    Include the full component

    – 

I think you might be making many unnecessary component updates.

Why not do this?

 Geocoder.from(location).then((json) => {
        const locResult = json.results[0].geometry.location;;
        genericLocations.forEach(async (type) => {
          const response = await fetch(
            `google places url`
          );
          const data = await response.json();

          const placesToOpen = data.results
          setPlacesOpen(current => [...current, ...placesToOpen]);
        });
      })

This will do only one setState instead of multiple ones. This should work and should update your local state.

Leave a Comment