P粉7399424052023-08-04 00:56:41
The problem is that you declare a variable called historicalDividend, initialize it to an empty array, and then reassign the entire variable to the time series data on each iteration, which means you overwrite the value each time. Also, entry is undefined, I think you might want to use date.
To solve all these problems, you should use the map() method, which accepts an array, loops over it, and creates a new array using the callback function return value.
As another tip: You should check the response's HTTP status code to make sure you're getting the expected response.
Here is a version of your code that fixes both issues:
async function fetchTimeSeriesDailyAdjusted(ticker) {
//Fetch function to get the daily close and the dividends
const apiTimeSeriesDailyAdjusted = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&apikey=${apiKey}`; //Lik of the API - update the symbol
try {
const response = await fetch(apiTimeSeriesDailyAdjusted);
// Check for HTTP response code
if (!response.ok) {
throw new Error(
$`Fetching daily time series data failed with status code '${response.status}'`
);
}
const data = await response.json();
const historicalDividend = data["Time Series (Daily)"].map(
(entry) => entry["7. dividend amount"]
);
console.log(historicalDividend); //Console log to see the dividend
return historicalDividend; //Value that the function must return
} catch (error) {
console.error("Error fetching apiTimeSeriesDailyAdjusted"); //Log of the error
}
}