Hoping to get some guidance on how to best work with async data calls in React.
I have a page that has a FullCalendar component which will show the events given to it in a state, i.e., simplifying a lot,
return (
...
<FullCalendar events={ events } />
)
What I need to do to get the events is first to make a call to Google Calendar's APIs to fetch the Oauthed user's calendars, then looping through each calendar, make a call to Google calendar to fetch that calendar's events. Something like (very simplified):
let eventsToShow = [];
apiCalendar.listCalendars({}).then(({result}) => {
// At this point I have the list of the user's calendars
result.items.forEach((calendar) => {
// Now I have all the events on a given calendar
apiCalendar.listEvents(calendar.id).then(({result}) => {
eventsToShow.push({id: result.id, start: result.start, end: result.end});
})
})
})
setEvents(eventsToShow);
Right now, I have a button on the page, and I'd like to kick off the calls to fetch the calendars and events when I click the button (because I have a separate button that does the Oauth sequence). Later, my intent is to store something from the Oauth so that the page will just pull the calendars and events automatically if the token is present.
In the above pseudocode, I have various pieces working - the FullCalendar component can show hard-coded events, my various API calls do fetch the correct date - but I'm having trouble figuring out how to put it all together.
I suspect I have to use a useEffect as well as use await, but the nested nature of the API calls is confusing me. If I do have to use useEffect, I'm also not sure how to get the calls to trigger off a button click for now.
I've tried having an onClick function for the button that just leads to essentially the second block of pseudocode above. This worked for causing the API calls to run (as evidenced by console.logs along the way), but the setEvents part at the end doesn't work, I suspect because of the async nature of things.
Help? Am I completely misguided?