the query
I'm facing an issue with displaying upcoming Google Calendar events on my Chrome extension using JavaScript and the Google Calendar API. The problem arises when I add new events on the Google Calendar website itself, as these events do not get refreshed or fetched by the extension. Even after signing out and re-authenticating, the new events are still not showing up, even though the old events display correctly.
An interesting observation is that this issue seems to be specific to certain calendars. Creating a new calendar seems to trigger a refresh of the events successfully.
approaches taken
As a novice in working with Google APIs, any guidance or suggestions would be greatly appreciated!
The current approach involves a function to fetch events from Google Calendar upon initial sign-in, which I assumed would also act as a refresh mechanism when retrieving data. However, for some calendars, this method fails to fetch new events. Suspecting a caching problem, I attempted to remove cache or include the 'Cache-Control': 'no-cache'
tag in the headers while fetching calendar data, but this did not resolve the issue.
snippet
This is the function used to fetch events:
chrome.identity.getAuthToken({interactive: true}, function(token) {
if (chrome.runtime.lastError) {
return;
}
console.log("Authentication successful. Token:", token);
isSignedIn = true;
localStorage.setItem('gcal-signed-in',"true");
var init = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
'contentType': 'json'
};
const now = new Date();
const isoNow = now.toISOString();
const maxResults = 4;
// retrieving all calendars
fetch(`https://www.googleapis.com/calendar/v3/users/me/calendarList`, init)
.then(response => response.json())
.then(calendarListData => {
calendarIds = calendarListData.items.map(calendar => calendar.id);
const fetchPromises = [];
let events = new Map();
// fetching most recent events from each calendar
for (const calendarId of calendarIds) {
const fetchPromise = fetch(`https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events?maxResults=${maxResults}&timeMin=${isoNow}`, init)
.then((response) => response.json())
.then((data) => {
if (data.items) {
data.items.forEach((event) => {
const dateTimeParts = event.start.dateTime.split('T');
const date = dateTimeParts[0];
const time = dateTimeParts[1].substring(0, 5);
const location = event.location;
console.log(location)
// trim gets rid of leading and trailing white space/commas
events.set([date, time], [event.summary.trim(),location]);
});
} else {
console.log("No upcoming events found.");
}
})
.catch((error) => {
console.error("Error fetching events:", error);
});
fetchPromises.push(fetchPromise);
}
// additional code for displaying the data using Promise.all(fetchPromises)
Your assistance is highly valued! Thank you.