Since 2009, we have been utilizing our extensive expertise in blockchain technologies to help businesses, both large and small, maximize their efficiency.
Explore More
With more than 400+ experts, Oodles comprises a fantastic resource of business knowledge that spans multiple industries. Whatever the circumstances, we keep to our obligations.
Explore More
At Oodles, we help our clients work with a human understanding but at superhuman speed something that others can't. They thus advance and maintain their lead
31st July 2023
22 min read
Associate Consultant - Frontend Development
This article gives you a guide to integrating Google Calendar API into the React application. A blockchain development company can use this API to integrate the feature of Google Calendar within its applications.
It is possible to incorporate Google Calendar API into your web application with such little coding. Here is a simple reference guide to aid with your knowledge. Most developers will find this article to be helpful in their endeavors.
Suggested Read | A Comprehensive List of Top dApp Development Platforms
You May Also Like | dApp (Decentralized App) Development | Increasing Importance
1. Setting up the Project
You should have nodejs and npm installed on your device. Now write the following command in your vs code to start your project.
npx create-react-app calendar
2. Adding files to the Project.
In the same directory as App.js, we will create a file called Calendar.js.
Now include the Calendar file in the App.js file:
import Calendar from './Calendar'
function App() {
return (
);
}
export default App;
Now, add the following code in the Calendar.js file:
import React, { useEffect } from "react";
export const Calendar = () => {
const gapi = window.gapi;
const google = window.google;
const CLIENT_ID =
"1084837142274-e4f0f7st0bb948hgvd40o9b7cg6g11ao.apps.googleusercontent.com";
const API_KEY = "AIzaSyD7_-bhPqIKNlnJN8OvPYAUql2Uyl5fD0Q";
const DISCOVERY_DOC =
"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest";
const SCOPES = "https://www.googleapis.com/auth/calendar";
const accessToken = localStorage.getItem("access_token");
const expiresIn = localStorage.getItem("expires_in");
let gapiInited = false,
gisInited = false,
tokenClient;
useEffect(() => {
//const expiryTime = new Date().getTime() + expiresIn * 1000;
gapiLoaded();
gisLoaded();
}, []);
function gapiLoaded() {
gapi.load("client", initializeGapiClient);
}
async function initializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
if (accessToken && expiresIn) {
gapi.client.setToken({
access_token: accessToken,
expires_in: expiresIn,
});
listUpcomingEvents();
}
}
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
DISCOVERY_DOC:
"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest",
callback: "", // defined later
});
gisInited = true;
}
//Enables user interaction after all libraries are loaded.
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error) {
throw resp;
}
await listUpcomingEvents();
const { access_token, expires_in } = gapi.client.getToken();
localStorage.setItem("access_token", access_token);
localStorage.setItem("expires_in", expires_in);
};
if (!(accessToken && expiresIn)) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({ prompt: "consent" });
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({ prompt: "" });
}
}
//Sign out the user upon button click.
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken("");
localStorage.clear();
}
}
async function listUpcomingEvents() {
let response;
try {
const request = {
calendarId: "primary",
timeMin: new Date().toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: "startTime",
};
response = await gapi.client.calendar.events.list(request);
} catch (err) {
document.getElementById("content").innerText = err.message;
return;
}
const events = response.result.items;
if (!events || events.length === 0) {
document.getElementById("content").innerText = "No events found.";
return;
}
// Flatten to string to display
const output = events.reduce(
(str, event) =>
`${str}${event.summary} (${
event.start.dateTime || event.start.date
})\n`,
"Events:\n"
);
document.getElementById("content").innerText = output;
}
function addManualEvent() {
var event = {
kind: "calendar#event",
summary: "Event 2",
location: "Masai School, Bangalore",
description: "Paty time",
start: {
dateTime: "2023-07-18T01:05:00.000Z",
timeZone: "UTC",
},
end: {
dateTime: "2023-07-18T01:35:00.000Z",
timeZone: "UTC",
},
recurrence: ["RRULE:FREQ=DAILY;COUNT=1"],
attendees: [
{ email: "[email protected]", responseStatus: "needsAction" },
],
reminders: {
useDefault: true,
},
guestsCanSeeOtherGuests: true,
};
var request = gapi.client.calendar.events.insert({
calendarId: "primary",
resource: event,
sendUpdates: "all",
});
request.execute(
(event) => {
console.log(event);
window.open(event.htmlLink);
},
(error) => {
console.error(error);
}
);
}
return (
);
};
export default Calendar;
Include the following script in the index.html file:
Also, Discover | A Comprehensive Exploration of Ordinal Marketplace Development
Now understanding the functions used in the calendar.js file.
const gapi = window.gapi;
const google = window.google;
const CLIENT_ID =
"1084837142274-e4f0f7st0bb948hgvd40o9b7cg6g11ao.apps.googleusercontent.com";
const API_KEY = "AIzaSyD7_-bhPqIKNlnJN8OvPYAUql2Uyl5fD0Q";
const DISCOVERY_DOC =
"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest";
const SCOPES = "https://www.googleapis.com/auth/calendar";
handleAuthClick()
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error) {
throw resp;
}
await listUpcomingEvents();
const { access_token, expires_in } = gapi.client.getToken();
localStorage.setItem("access_token", access_token);
localStorage.setItem("expires_in", expires_in);
};
if (!(accessToken && expiresIn)) {
tokenClient.requestAccessToken({ prompt: "consent" });
} else {
tokenClient.requestAccessToken({ prompt: "" });
}
}
This function is called when the "Authorize" button is clicked. It sets the tokenClient.callback to handle the response after the user grants authorization. If there is no access token and expiration time the localStorage, it prompts the user to select a Google Account and grant consent to access their calendar data by calling tokenClient.requestAccessToken({ prompt: "consent" }). If there is an existing session, it requests an access token without displaying the account chooser and consent dialog.
function addManualEvent() {
var event = {
kind: "calendar#event",
summary: "Event 2",
location: "Masai School, Bangalore",
description: "Paty time",
start: {
dateTime: "2023-07-18T01:05:00.000Z",
timeZone: "UTC",
},
end: {
dateTime: "2023-07-18T01:35:00.000Z",
timeZone: "UTC",
},
recurrence: ["RRULE:FREQ=DAILY;COUNT=1"],
attendees: [
{ email: "[email protected]", responseStatus: "needsAction" },
],
reminders: {
useDefault: true,
},
guestsCanSeeOtherGuests: true,
};
var request = gapi.client.calendar.events.insert({
calendarId: "primary",
resource: event,
sendUpdates: "all",
});
request.execute(
(event) => {
console.log(event);
window.open(event.htmlLink);
},
(error) => {
console.error(error);
}
);
}
This function adds a new manual event to the user's primary calendar. It constructs an event object with details such as summary, location, description, start and end times, recurrence, attendees, and reminders. Then, it uses gapi.client.calendar.events.insert to send a request to insert the event into the calendar. Upon successful insertion, it opens a new window with the link to the created event.
Check It Out | A Beginner's Guide to Web App Development
async function listUpcomingEvents() {
let response;
try {
const request = {
calendarId: "primary",
timeMin: new Date().toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: "startTime",
};
response = await gapi.client.calendar.events.list(request);
} catch (err) {
document.getElementById("content").innerText = err.message;
return;
}
const events = response.result.items;
if (!events || events.length === 0) {
document.getElementById("content").innerText = "No events found.";
return;
}
const output = events.reduce(
(str, event) =>
`${str}${event.summary} (${
event.start.dateTime || event.start.date
})\n`,
"Events:\n"
);
document.getElementById("content").innerText = output;
}
It retrieves the user's upcoming calendar events. It makes an API call to the Google Calendar API using gapi.client.calendar.events.list(request) to fetch events from the user's primary calendar. The events are then displayed on the web page.
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken("");
localStorage.clear();
}
}
On clicking the sign-out button. It revokes the user's access token, clears the client token, and removes the access token and expiration time from localStorage, effectively signing the user out.
Everything is now operational. You should see the event scheduler screen if you followed the steps correctly.
If you require any assistance in adding features like Google Calendar to your decentralized application, then connect with our blockchain developers.
Neha Chauhan
Neha is a skilled Frontend Developer with proficiency in a range of technologies including JavaScript, HTML5, CSS, and ReactJS. She has worked on several successful client projects, including Mister Z - an ICO platform for investors to participate in incubated ideas, and an access control app project. Neha is committed to constantly improving her skills and staying up-to-date with the latest industry trends and advancements to ensure she delivers the best possible outcomes.
Associate Consultant - Frontend Development
By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.
We would love to
hear from you!
Innovate with confidence!