Here is a summary of what I'm trying to do:
- Make a call to an AOU using the accountId - this returns an array of items.
- I need to use the item.ReportDate to make another call to the AOU to get projects.
- I map the ReportDates to a variable
- I set a new empty array variable named projects
- Loop through ReportDates.Items and push the items into projects
- Now when I console.log projects, it shows a list of projects however if I try to access them individually like projects[0], it gives back undefined. I am assuming this is due to it being async.
How can I access the resolved projects?
Here is a shortened version of what the data calls look like:
// First api call to retrieve ReportDates:
fetch(baseUrl + "api/Woh/Summary/" + accountId):
AccountId.Items: [
{
AccountId: 124,
clientName: XYZ,
reportDate: "2018-09-30"
},
{
AccountId: 124,
clientName: XYZ,
reportDate: "2018-09-20"
},
]
// Next using a loop to make fetch calls using reportDates:
fetch(baseUrl + "api/Woh/Details/" + accountId + "/" + reportDate)
reportDate.Items(first loop):
[
{a:y},
{b:z},
{c:v}
]
reportDate.Items(second loop):
[
{a:y},
{b:z}
]
Now I'm trying to push all the items in each call to compile it all into 1 array. And that's where I'm having trouble accessing after the loop is complete.
Here is my code:
const getProjectsData = async () => {
let projectsData = await fetch(baseUrl + "api/Woh/Summary/" + accountId);
let projectsJson = await projectsData.json();
let reportDates = projectsJson.Items.map(item => formatDate(item.ReportDate));
let projects = [];
reportDates.forEach(reportDate => {
fetch(baseUrl + "api/Woh/Details/" + accountId + "/" + reportDate)
.then(res => res.json())
.then(data => {
data.Items.forEach(item => projects.push(item));
})
});
console.log(dates);
// console logging dates shows the array of items that I want, but when I try to access them individually with dates[0], it shows as undefined.
}