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.
CodePudding user response:
Are you even entering your Promise.all
sequence to begin with?
You are already ending the promise by having a .then
function after getting the stockdata.
stocksList.map((stock) => {
promises.push(
getStocksData(stock)
)
})
Promise.all(promises).then((result)=>{
const tempStocks = result.map((stock) => {
return {
name: stock.name,
data: stock.data
}
});
console.log(tempStocksData)
setStockData(tempStocksData)
console.log(stockData)
})
Note: Above code is untested but is made to show the point
CodePudding user response:
Try using the spread operator when you setStockData
like this
setStockData([...tempStocksData])