I am new to React, and I am currently trying to figure out a way to call a function only after two state variables have been updated. These state variables are updated after running fetch on my backend, but the function I am trying to call keeps returning an error because it is being called before the variables have been set. I have been trying to useEffect and async, but I feel like I am missing something. I want to call "calculateRec" after coinbasePrices and binancePrices has been set using the data from fetch. Any help would be greatly appreciated!
const [coinbasePrices, setCoinbasePrices] = useState([]);
const [binancePrices, setBinancePrices] = useState([]);
const [recommendations, setRecommendations] = useState({});
useEffect(() => {
(async () => {
await fetch('http://localhost:8080/prices/coinbase').then(res => res.json())
.then((data) => {
setCoinbasePrices(reformatPrices(data))
})
.catch(err => { throw err });
await fetch('http://localhost:8080/prices/binance').then(res => res.json())
.then((data) => {
setBinancePrices(reformatPrices(data))
})
.catch(err => { throw err });
setRecommendations(calculateRec(coinbasePrices, binancePrices));
})();
}, []);