'API doesn't call with a variable. React.js, moment-business-days
I have been stuck on this problem for a while now, so I think it is time to ask my cool worldwide geniuses.
What I am trying to do: Create An array of arrays that pairs a date and data automatically (through a loop). Complicating factors including trying to get dates of only weekdays and exclude holidays.
Problem: When I use a variable, the API data doesn't display. This particular line is the problem arrayOfDateAndPrice.push(data[2].data['Time Series (Daily)'][today]['4. close'])
the 'data' holds the API that I am fetching. I am digging through the JSON in data[2].data['Time Series'] etc. When I insert the date with a variable (i.e date I got from the loop, I checked, it fetches the correct date in string format). it doesn't work. BUT, when I insert a stringed normal date (i.e. '2022-03-04') it displays the data!? What the heck am I missing?
Error: TypeError: undefined is not an object (evaluating 'data[2].data['Time Series (Daily)'][today]['4. close']')
const calculateBusinessDay = (data) => {
const presDay = '02-21-2022';
const goodFri = '04-15-2022';
const memDay = '05-30-2022';
const junTeenth = '06-20-2022';
const july4th = '07-04-2022';
const laborDay = '09-05-2022';
const thanksGiving = '11-24-2022';
const xMas = '12-26-2022';
var today;
var arrayOfDateAndPrice = [];
const arrayOfAllData = [];
const weekdays = momentBusiness
weekdays.updateLocale('us', {
holidays: [mlk, presDay, goodFri, memDay, junTeenth, july4th, laborDay, thanksGiving, xMas],
holidayFormat: 'MM-DD-YYYY',
workingWeekdays: [1, 2, 3, 4, 5]
});
for (let i = 0; i < 30; i++) {
today = weekdays().subtract(i, 'days').format('YYYY-MM-DD')
if (weekdays(today).isBusinessDay() && !weekdays(today).isHoliday() == true) {
arrayOfDateAndPrice.push(today)
arrayOfDateAndPrice.push(data[2].data['Time Series (Daily)'][today]['4. close'])
arrayOfAllData.push(arrayOfDateAndPrice)
arrayOfDateAndPrice = [];
}
}
return (
arrayOfAllData
)
}
Solution 1:[1]
I figured it out?!?! It was because my 'i' variable started the day from "today" which was Japan time. No market data for Japan time since we are "ahead" in time lol. Oh gosh. That feels good...
The 'i' had to start at i=1, to subtract one day from today and start the loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mikeduges |
