Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
Running a function when it's previous function completes in React/React Native

I have 2 functions which I want to run one after the other but as the 2nd function gets info from the state created in the previous function, I want it to wait for that to finish before executing.

I know async/await is likely the best for this but haven't fully grasped it just yet.

The first function essentially grab the nearest location from a set of data and sets state to the first item from that data, then the second function will move the map to that location from the latitude/longitude of the previous function.

This is my code currently:

  const nearestPod = () => {
    let newArr = [];
    let closest = [];

    data.map(item => newArr.push(item.distance));
    newArr.sort(function (a, b) {
      return a - b;
    });

    data.map(item => item.distance == newArr[0] && closest.push(item));
    setClosestPod(closest);

    setNearestActive(true);
    moveToNearestPod();
  };

  const moveToNearestPod = async () => {
    await nearestPod();
    let lat = closestPod[0].lat;
    let lng = closestPod[0].lng;

    setLat(lat);
    setLng(lng);
  };

This function does work but only on the 2nd click and throws me Promise Rejection warnings so feel i'm close to getting it right, but if anyone could provide some expertise so I know best practice moving forward, I would greatly appreciate it!

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

None of this needs to async. But React queues and processes state updates in batches so you need to use useEffect to pick up the changes to those state changes, and then set your lat/lng states.

Note: map creates a new array, so you don't need to declare your arrays beforehand (otherwise use forEach). And, that second example should probably use find. It will return one object that matches the condition.

function nearestPod() {

  const newArr = data.map(item => item.distance);

  newArr.sort((a, b) => a - b);

  const closest = data.find(item => item.distance === newArr[0]);

  setClosestPod(closest);
  setNearestActive(true);

};

useEffect(() => {
  let lat = closestPod.lat;
  let lng = closestPod.lng;
  setLat(lat);
  setLng(lng);
}, [closestPod]);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!