My useEffect populates tempStocksData, which is passed into setStockData() when the Promise is fulfilled. As shown in the code below, print out tempStocksData and stockData, which is supposed to be populated since I called setStockData(tempStocksData). You can see that Promise is fulfilled since it executes the prints. However, stockData is empty. For some reason setStockData is not working since stockData is not being populated. Below is the code for reference:
const [ stockData, setStockData ] = useState([])
const getStocksData = (stock) => {
return axios.get(`${BASE_URL}?symbol=${stock}&token=${TOKEN}`).catch((error) => {
console.error("Error", error.message)
})
}
useEffect(()=> {
let tempStocksData = []
const stocksList = ["AAPL", "MSFT", "TSLA", "FB", "BABA", "UBER", "DIS", "SBUX"];
let promises = [];
stocksList.map((stock) => {
promises.push(
getStocksData(stock)
.then((res) =>
{tempStocksData.push({
name: stock,
...res.data
})
})
)
})
Promise.all(promises).then(()=>{
console.log(tempStocksData)
setStockData(tempStocksData)
console.log(stockData)
})
}, [])
Please help me resolve this issue. Let me know if there is something I'm missing or something that I'm doing that is not up to date with versions/dependencies or if I'm doing Promise() js wrong.