0

Heres a picture of what the browser console says when I do console.log(portfolio) where portfolio is the array. As you can see, it says the array is full of zeros but then also contains other numbers that aren't 0 in the same indices.

Picture of Array Values(https://i.stack.imgur.com/hWr68.png)

If I do portfolio[i] for any i between 0 and 29, I get 0. I want to get the other number such as 1257.72 for portfolio[0]. Thanks.

Here's the code:

let portfolioValue = []
useEffect(() => {

        for (let i = 0; i < 30; i++) {
            portfolioValue[i] = 0;
        }

        stocks.forEach(stock => {
            const fetchData = async () => {
                const response = await fetch(`https://api.twelvedata.com/time_series?symbol=${stock.ticker}&interval=1day&output=10&apikey=${key}`)
                const data = await response.json()

                for (let i = 0; i < 30; i++) {
                    portfolioValue[i] += (data.values[i].close * stock.numShares)
                }
            }
    
            fetchData()
        })

        console.log(portfolioValue);

    }, [user])
coder
  • 3
  • 2
  • Can you provide the data of this ```portfolio```? Add some code just in case. – Newbee Apr 15 '23 at 00:47
  • ```portfolioValue[i] = 0;``` you are looping your data with name **0**. Can you add image/draft what will be the final output you want to achieve? – Newbee Apr 15 '23 at 01:06
  • This is the final output I want https://imgur.com/Njf0P1d – coder Apr 15 '23 at 01:26
  • Can you also show how the stock data looks like? eh the Num shares in particular. – Onyambu Apr 15 '23 at 02:09
  • Provide some data for these ```data.values.close``` and ```stock.numShares``` for easy debugging. – Newbee Apr 15 '23 at 02:21
  • The code doesn't wait for the promises returned by `fetchData` to be fulfilled before trying to access `portfolio` data, so the unexpanded log shows the zeroes it was initialised with. When the log of the array was manually expanded (some time later) the data had arrived and could be shown in the expanded item list. Use `map` instead of `forEach` and pass the promise array through `Promise.all` before using the results. – traktor Apr 15 '23 at 05:12

0 Answers0