I'm writing an asynchronous function in React that should set the "coords" state to an array of objects containing US states and their respective latitudes/longitudes. To do this, I'm making an API call and resolving those calls using Promise.all. On the first refresh of the page, the function works as intended. However, on subsequent refreshes, the function does not execute the Promise.all statement and therefore does not set the coords state. Why is this the case and how can I resolve this issue?
export default function App() {
const [covidDataJSON, setCovidDataJSON] = useState(null);
const [stateNames, setStateNames] = useState([]);
const [coords, setCoords] = useState([]);
const [stateInfos, setStateInfos] = useState([]);
useEffect(() => {
fetchCoords();
}, [])
const fetchCoords = async () => {
try {
getStateNames();
const req = await Promise.all(stateNames.map(async (state) => {
return await axios.get(`https://nominatim.geocoding.ai/search.php?state=${state}&format=jsonv2`);
}))
for (let i = 0; i < req.length; i++){
const stateInfo = req[i].data[0];
if (req[i].data.length !== 0)
setCoords(coordsArr => [...coordsArr, {name: stateInfo.display_name, lat: stateInfo.lat, lon: stateInfo.lon}]);
}
} catch (err) {
console.error(err);
}
};
const getStateNames = () => {
try {
const stateArr = [];
for (let i = 0; i < states.length; i++){
stateArr.push(states[i].name);
}
setStateNames(stateArr);
} catch (error) {
console.error(error);
}
}