1

I fetch this array from server :

[{
  "res_id": 0,
  "res_name": "string",
  "res_desc": "string",
  "res_address": "string"
},
etc
]

I have to display a list of markers on map, so I map my restos into marker to populate the coords, the first problem is with the data i get from server, its an adress, so then I call:

restos.forEach(x => FetchGeocoder(x.res_address));

To then fetch with geocoder:

const FetchGeocoder = async (address) => {
        const response = await fetch('https://maps.googleapis.com/maps/api/geocode/json?address=' +
            address + ',' +
            'CABA&key=' + "KEY")
        const responseData = await response.json();
        const markers = responseData.results[0].geometry.location;
        restos.forEach(x => {
            x.res_coords = {
                latitude: markers.lat,
                longitude: markers.lng
            }
        });
    };

The problem I cant resolve is that I get 3 coords objects, because I have 3 restos in my array, but only 1 coords object is assigned to all of my restos, instead of each coords beeing asigned to the correct resto.

Thanks in advance for any help or assistance!

1 Answer 1

1

One option would be to make use of async/await to perform asynchronous function calls (ie to fetchGeocode()) during each iteration of the restos array.

For example, you could adapt your code to use the following (or similar) pattern:

/* Define async fetchGeocode() function that returns lat/lng data */
const fetchGeocode = async (address) => {
  const res = await fetch('https://maps.googleapis.com/maps/api/geocode/json' + 
                          '?address=' + address + ',CABA&key=' + API_KEY);

  const json = await res.json();
  const { lat, lng } = json.results[0].geometry.location;

  return {
    latitude: lat,
    longitude: lng
  };
};

// Async function adds coords to each resto
async function addCoordsToRestos(restos) => {

  // If restos undefined, or not an iterable array type then return
  // an empty array as a default response
  if(!Array.isArray(restos)) {
      return [];
  }

  // Iterate each resto
  for (const resto of restos) {

    // Mutate current resto by adding res_coords. Call fetchGeocode() 
    // with await to wait for async function to complete before next
    // iteration
    resto.res_coords = await fetchGeocode(resto.res_address);
  }

  // Return mutated restos array to next handler
  return restos
}

Usage would then look like this:

// If called inside an async function
await addCoordsToRestos( restos );

Or:

// If called as a promise
addCoordsToRestos( restos ).then(() => { console.log('done') });
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, the problem now is that i get restos from useSelector using redux, how can i implement your iterator? I get TypeError: undefined is not an object (evaluating '_iterator')] when using your approach.
your'e welcome - it seems like the restos may be undefined which will mean the need for additional checks before running the code above. I'll make some changes to my answer that might point you in the right direction

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.