Home > Software design >  How can I get an async function to update on a button onClick in React?
How can I get an async function to update on a button onClick in React?

Time:08-01

I'm creating an app that gets data from a Error message

How can I get the async function to properly return the JSON in one call?

Thanks for the help!

CodePudding user response:

Issue

The problem is that this line Promise.all([fetchCoordinates(), getPlaces()]); that you have inside FinalSearch would resolve the two promises randomly, there isn't an order.

And even if there was an ordre, the updated state by fetchCoordinates would not have taken effect by the time getPlaces is called, as a re-render of the component is needed to update a state.

Solution

One way to sole this issue is first to change fetchCoordinates so that it returns that array of lat and log, something like so:

async function fetchCoordinates() {
  setLocation({
    city: {
      name: city,
    },
    state: {
      name: state,
    },
  });
  const res = await fetch(
    `https://api.geoapify.com/v1/geocode/search?text=${city.concat(
      ", ",
      state
    )}&format=json&apiKey=API_KEY`
  );
  const data = await res.json();
  const filtredData = data.results.filter((x) => x.result_type === "city");
  setCoordinates(
    !filtredData[0].lat && !filtredData[0].long ? "" : [filtredData[0].lat, filtredData[0].lon]
  );
  return [filtredData[0].lat, filtredData[0].lon];
}

Change getPlaces so that it takes lat, and log as parameter:

async function getPlaces(lat, long) {
  const res = await fetch(
    `https://api.geoapify.com/v2/places?categories=office.charity,office.association,office.non_profit&filter=circle:${long},${lat},5000&bias=proximity:${long},${lat}&limit=20&apiKey=API_KEY`
  );
  const data = res.json();
  setResults(data);
}

Change FinalSearch so that it gives the coordinates returned by fetchCoordinates to getPlaces.

async function FinalSearch() {
  try {
    const cordinates = await fetchCoordinates();
    getPlaces(...cordinates);
  } catch (error) {
    console.log(err);
    return [null, null, null];
  }
}
  • Related