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.
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]);