A Guide to Google Calendar API Integration into Your React Application

Posted By : Neha

Jul 26, 2023

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. 

 

Motivation

 

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

 

All Requirements

 

  • Creating a calendar app project
  • Setting up the components for it
  • Understanding the core functions that are needed for the project
  • Connecting all things up

 

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 (

<div className="App">

<Calendar/>

</div>

);

}

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 (

<div>

<button

id="authorize_button"

hidden={accessToken && expiresIn}

onClick={handleAuthClick}

>

Authorize

</button>

<button

id="signout_button"

hidden={!accessToken && !expiresIn}

onClick={handleSignoutClick}

>

Sign Out

</button>

<button

id="add_manual_event"

hidden={!accessToken && !expiresIn}

onClick={addManualEvent}

>

Add Event

</button>

<pre id="content" style={{ whiteSpace: "pre-wrap" }}></pre>

</div>

);

};

 

export default Calendar;

 

 

Include the following script in the index.html file:

 

<script

src="https://apis.google.com/js/api.js"

type="text/javascript"

></script>

<script

src="https://accounts.google.com/gsi/client"

type="text/javascript"

></script>

 

Also, Discover | A Comprehensive Exploration of Ordinal Marketplace Development

 

Functions Used in Calendar.js

 

Now understanding the functions used in the calendar.js file.

 

1. Gapi Initialization Function that Allows the Program to Access Google and Manage the Rest

 

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";

 

2. 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.

 

3. To Add Events Manually in Google Calendar

 

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 

 

4. Listing Up all the Events You Entered or are Already Present in Your Calendar

 

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. 

 

5. Function that Signs Out a User

 

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

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

November 18, 2024 at 12:18 pm

Your comment is awaiting moderation.

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.

Chat with Us
Telegram Button
Youtube Button

Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text