Giter Site home page Giter Site logo

kubessandra / react-google-calendar-api Goto Github PK

View Code? Open in Web Editor NEW
212.0 6.0 89.0 2.23 MB

An api to manage your google calendar

License: MIT License

JavaScript 21.12% TypeScript 66.40% HTML 10.29% CSS 2.19%
reactjs google-api google-calendar-api typescript manage

react-google-calendar-api's Introduction

react-google-calendar-api

Build Status npm (custom registry) npm (downloads) Gitter chat

An api to manage your google calendar

Install

Npm

npm install --save react-google-calendar-api

yarn

yarn add react-google-calendar-api

Use (Javascript / Typescript)

You will need to enable the "Google Calendar API"(https://console.developers.google.com/flows/enableapi?apiid=calendar.) You will need a clientId and ApiKey from Google(https://developers.google.com/workspace/guides/create-credentials)

import ApiCalendar from "react-google-calendar-api";

const config = {
  clientId: "<CLIENT_ID>",
  apiKey: "<API_KEY>",
  scope: "https://www.googleapis.com/auth/calendar",
  discoveryDocs: [
    "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest",
  ],
};

const apiCalendar = new ApiCalendar(config);

Setup

handleAuthClick:

    /**
     * Sign in with a Google account.
     * @returns {any} A Promise that is fulfilled with the GoogleUser instance when the user successfully authenticates and grants the requested scopes, or rejected with an object containing an error property if an error happened
     */
    public handleAuthClick(): void

handleSignOutClick:

    /**
     * Sign out user google account
     */
    public handleSignoutClick(): void

Example

  import React, {ReactNode, SyntheticEvent} from 'react';
  import ApiCalendar from 'react-google-calendar-api';

  const config = {
    "clientId": "<CLIENT_ID>",
    "apiKey": "<API_KEY>",
    "scope": "https://www.googleapis.com/auth/calendar",
    "discoveryDocs": [
      "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"
    ]
  }

  const apiCalendar = new ApiCalendar(config)

  export default class DoubleButton extends React.Component {
      constructor(props) {
        super(props);
        this.handleItemClick = this.handleItemClick.bind(this);
      }

      public handleItemClick(event: SyntheticEvent<any>, name: string): void {
        if (name === 'sign-in') {
          apiCalendar.handleAuthClick()
        } else if (name === 'sign-out') {
          apiCalendar.handleSignoutClick();
        }
      }

      render(): ReactNode {
        return (
              <button
                  onClick={(e) => this.handleItemClick(e, 'sign-in')}
              >
                sign-in
              </button>
              <button
                  onClick={(e) => this.handleItemClick(e, 'sign-out')}
              >
                sign-out
              </button>
          );
      }
  }

setCalendar:

    /**
     * Set the default attribute calendar
     * @param {string} newCalendar ID.
     */
    public setCalendar(newCalendar: string): void

Manage Event

You need to be registered with handleAuthClick.

Create Event:

    /**
    * Create calendar event
    * @param {string} CalendarId for the event by default use 'primary'.
    * @param {object} Event with start and end dateTime
    * @param {string} sendUpdates Acceptable values are: "all", "externalOnly", "none"
    * @returns {any} Promise on the event.
    */
   public createEvent(event: object, calendarId: string = this.calendar, sendUpdates: string = 'none',): any

Create Event From Now:

     /**
     * Create an event from the current time for a certain period.
     * @param {number} Time in minutes for the event
     * @param {string} Summary(Title) of the event
     * @param {string} Description of the event (optional)
     * @param {string} CalendarId by default calendar set by setCalendar.
     * @param {string} timeZone The time zone in which the time is specified. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".)
     * @returns {any} Promise on the event.
     */
    public createEventFromNow({time, summary, description = ''}: any, calendarId: string = this.calendar, timeZone: string = "Europe/Paris"): any

Create Event With Video Conference:

     /**
     * Create Calendar event with video conference
     * @param {object} event with start and end dateTime
     * @param {string} calendarId for the event.
     * @param {string} sendUpdates Acceptable values are: "all", "externalOnly", "none"
     * @returns {any}
     */
  public createEventWithVideoConference(
    event: any,
    calendarId: string = this.calendar,
    sendUpdates: "all" | "externalOnly" | "none" = "none"
  ): any

Example

import ApiCalendar from "react-google-calendar-api";

const config = {
  clientId: "<CLIENT_ID>",
  apiKey: "<API_KEY>",
  scope: "https://www.googleapis.com/auth/calendar",
  discoveryDocs: [
    "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest",
  ],
};

const apiCalendar = new ApiCalendar(config);

const eventFromNow: object = {
  summary: "Poc Dev From Now",
  time: 480,
};

apiCalendar
  .createEventFromNow(eventFromNow)
  .then((result: object) => {
    console.log(result);
  })
  .catch((error: any) => {
    console.log(error);
  });

const eventWithVideoConference: object = {
  summary: "Event With Google Meet Conference",
  start: {
    dateTime: new Date().toISOString(),
    timeZone: "Europe/Paris",
  },
  end: {
    dateTime: new Date(new Date().getTime() + 3600000).toISOString(),
    timeZone: "Europe/Paris",
  },
};

apiCalendar
  .createEventWithVideoConference(eventWithVideoConference)
  .then((result: object) => {
    console.log(result);
  })
  .catch((error: any) => {
    console.log(error);
  });

List All Upcoming Events:

    /**
     * List all events in the calendar
     * @param {number} maxResults to see
     * @param {string} calendarId to see by default use the calendar attribute
     * @returns {any} Promise with the result.
     */
    public listUpcomingEvents(maxResults: number, calendarId: string = this.calendar): any

Example

  // The user need to signIn with Handle AuthClick before
  apiCalendar.listUpcomingEvents(10).then(({ result }: any) => {
    console.log(result.items);

List All Events:

    /**
     * List all events in the calendar queried by custom query options
     * See all available options here https://developers.google.com/calendar/v3/reference/events/list
     * @param {object} queryOptions to see
     * @param {string} calendarId to see by default use the calendar attribute
     * @returns {any}
     */
    public listEvents(queryOptions, calendarId = this.calendar): any

Example

  // The user need to signIn with Handle AuthClick before
  apiCalendar.listEvents({
      timeMin: new Date()..toISOString(),
      timeMax: new Date().addDays(10).toISOString(),
      showDeleted: true,
      maxResults: 10,
      orderBy: 'updated'
  }).then(({ result }: any) => {
    console.log(result.items);
  });

Update Event

   /**
    * Update Calendar event
    * @param {string} calendarId for the event.
    * @param {string} eventId of the event.
    * @param {object} event with details to update, e.g. summary
    * @param {string} sendUpdates Acceptable values are: "all", "externalOnly", "none"
    * @returns {any} Promise object with result
    */
   public updateEvent(event: object, eventId: string, calendarId: string = this.calendar, sendUpdates: string = 'none'): any

Example

const event = {
  summary: "New Event Title",
};

apiCalendar.updateEvent(event, "2eo85lmjkkd2i63uo3lhi8a2cq").then(console.log);

Delete Event

   /**
   * Delete an event in the calendar.
   * @param {string} eventId of the event to delete.
   * @param {string} calendarId where the event is.
   * @returns {any} Promise resolved when the event is deleted.
   */
   public deleteEvent(eventId: string, calendarId: string = this.calendar): any

Example

apiCalendar.deleteEvent("2eo85lmjkkd2i63uo3lhi8a2cq").then(console.log);

Get Event

   /**
   * Get Calendar event
   * @param {string} calendarId for the event.
   * @param {string} eventId specifies individual event
   * @returns {any}
   */
   public getEvent(eventId: string, calendarId: string = this.calendar): any

Example

apiCalendar.getEvent("2eo85lmjkkd2i63uo3lhi8a2cq").then(console.log);

react-google-calendar-api's People

Contributors

asymons avatar bateradt avatar chantelc-mb avatar clariceabreu avatar dependabot[bot] avatar hellorupa avatar kubessandra avatar mttpla avatar ochotadariusz avatar oscarcusin avatar ryokochang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-google-calendar-api's Issues

Repeat created event

The google calendar api gives you the option to repeat events daily weekly etc. I did not see this implementation in you your documentation or did I miss something?

Migrate to Google Identity Services

Google is deprecating a lot of the code used in this library. This code will not be usable for people who are starting new projects and is only usable for one more year for existing projects. I used this link (https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#gis-and-gapi) to migrate my current app over (I don't use your library), and wanted to address this issue here in case anyone runs in to this issue

Here is the email I received below:

You are receiving this message because one or more of your web applications uses the legacy Google Sign-In web solution.

Our announced plan earlier this month stated that authorization support for the Google Sign-In JavaScript platform library will no longer be supported after March 31, 2023.

Beginning April 30th, 2022, new applications must use the Google Identity Services library, while existing apps may continue using the Platform Library until the deprecation date.

After March 31, 2023, migration to the new Google Identity Services will be necessary to sign in customers using their Google Account to your platform. The SDK will use the new Sign In With Google client library.

ApiCalendar.sign is always false on first load.

When refresh while logged in, ApiCalendar.sign will return false on reload, but I am already logged in.

I have a login and logout button but on load it will show the login button:

let button;

if (ApiCalendar.sign) {
	button = <button onClick={(e) => this.handleItemClick(e, 'sign-out')}> sign-out </button>
} else {
	button = <button onClick={(e) => this.handleItemClick(e, 'sign-in')}> sign-in </button>;
}

Content Security Policy Issue

Getting this error when the page loads:

Content Security Policy: The page’s settings blocked the loading of a resource at https://apis.google.com/js/api.js (“script-src”).

Here are my meta tags in my index.html

<meta 
    http-equiv="Content-Security-Policy"
    content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://apis.google.com"
/>
<meta
    http-equiv="Content-Security-Policy"
    content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://accounts.google.com"
/>

Here is the code from my component

import ApiCalendar from "react-google-calendar-api";

function Calendar() {
	ApiCalendar.onLoad(() => {
		ApiCalendar.handleAuthClick()
			.then(() => {
				console.log("sign in succesful!");
			})
			.catch((e) => {
				console.error(`sign in failed ${e}`);
			});
	});
	if (ApiCalendar.sign)
		ApiCalendar.listUpcomingEvents(10).then(({ result }) => {
			console.log(result.items);
		});
	return <div>Calendar</div>;
}

export default Calendar;

I'm just trying to console.log the events right now but it's not working. Any help would be appreciated.

ReferenceError: Can't find variable: document

I am using [email protected] and getting error ReferenceError: Can't find variable: document on iPhone 8 simulator. However, it works fine on web browser using npm run web to execute expo start --web command on my system

Error

ReferenceError: Can't find variable: document

This error is located at:
    in GoogleApiProvider (created by App)
    in App (created by ExpoRoot)
    in ExpoRoot
    in RCTView (created by View)
    in View (created by AppContainer)
    in DevAppContainer (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:95:4 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:141:19 in handleException
at node_modules/react-native/Libraries/Core/ReactFiberErrorDialog.js:52:4 in showErrorDialog
at node_modules/react-native/Libraries/ReactNative/renderApplication.js:76:4 in renderApplication
at node_modules/react-native/Libraries/ReactNative/AppRegistry.js:119:25 in runnables.appKey.run
at node_modules/react-native/Libraries/ReactNative/AppRegistry.js:213:4 in runApplication

Environment Information


npm -v
6.4.1
node -v
v12.22.12
"dependencies": {
    "expo": "~45.0.0",
    "expo-status-bar": "~1.3.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-gapi": "^1.0.2",
    "react-google-calendar-api": "^2.0.3",
    "react-native": "0.68.2",
    "react-native-web": "0.17.7"
 }

Add new features getBasicProfile, get and Delete and improve event createEventFromNow

Hello everyone, first of all thanks for this library being very useful and helping me a lot.

I need to add new events to this library, I will do a PR with the new features below:

getBasicProfile () - https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile
get () - https://developers.google.com/calendar/v3/reference/events/get
delete () - https://developers.google.com/calendar/v3/reference/events/delete

I saw that some resources above have a PR, but were never closed, so basically I merged these changes with my branch and added just getBasicProfile.

I hope this helps the community

Thank you.

this.gapi not loaded

I am getting error while trying to ApiCalendar.handleAuthClick()
Error: this.gapi not loaded

Listing available calendars

Hello,
How can I list available calendars in order to be able to pick one with setCalendar()?
Best,
George

Make config reffered to absolute path

./node_modules/react-google-calendar-api/ApiCalendar.js
Cannot find module: '../../../apiGoogleconfig.json'. Make sure this package is installed.

make it absolute path

[CustomList] Mehtod to list events using input custom options

Besides listUpcomingEvents it would be nice to have a method listEvents that receive the list query options as parameter, enabling custom fetches.
The method could be like that:

/**
   * List all events in the calendar queried by custom query options
   * See all available options here https://developers.google.com/calendar/v3/reference/events/list
   * @param {object} queryOptions to see
   * @param {string} calendarId to see by default use the calendar attribute
   * @returns {any}
   */
  public listEvents(
    queryOptions: object,
    calendarId: string = this.calendar
  ): any {
    if (this.gapi) {
      return this.gapi.client.calendar.events.list({
        calendarId,
        ...queryOptions
      });
    } else {
      console.log('Error: this.gapi not loaded');
      return false;
    }
  }

Send Updates

I saw a closed issue for Send Updates being added. Did this ever happen?

ApiCalendar any type

Variable 'ApiCalendar' implicitly has type 'any' in some locations where its type cannot be determined.ts(7034)

Build parse error

Eslint error on build/Apicalendar.js

Module parse failed: Unexpected token (199:16)
You may need an appropriate loader to handle this file type.
return this.gapi.client.calendar.events.list({
'calendarId': calendarId,
...queryOptions
});
} else {

you solved this issue on src files

ApiCalendar has type `any`

When trying to import the API Calendar using import ApiCalendar from 'react-google-calendar-api/ApiCalendar';, I get the following error:

Variable 'ApiCalendar' implicitly has type 'any' in some locations where its type cannot be determined. ts(7034)

I am trying to use the DoubleButton from the example.

handleAuthClick() always returns undefined

In docs, it says that handleAuthClick() returns a promise, but it does not. I need this so that after the user approves permission for the calendar, I can load all the events. Without it, I can't know if permission is granted or not.

gapi not loaded

I'm trying to run the example, but i have this error.

ReactNativeJS: Error: this.gapi not loaded

Gapi deprication

R u planning to change auth method, because from 31 march 2023 gapi is depricated, i am planning to use lib for long term, but if u r not planning to change something pls let me know

ApiCalendar.handleAuthClick() returns undefined

hello thanks for your great work
i was using this library almost 3 month ago and it worked fine but now when i want to use it i canstantlly get this error
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'getAuthInstance')

if anyone can help me that would be great

problem trying to create meets link and sending mail notification when creating a new event

Hi,

i'm using the api to manage the creation of events but i'm failing to auto generate a google meets link, also failing to send the invitation to the event to the attendees, is there any way to do so using this api?

i'll attach the method i have written this far trying to solve this issue

export function setNewEvents(event) {
	let r = Math.random().toString(36).substring(7);
	let options = {
		summary: event.summary,
		start: {
			dateTime: event.start,
		},
		end: {
			dateTime: event.end,
		},
		attendees: [{ email: "[email protected]", responseStatus: "needsAction" }],
		conferenceData: {
			createRequest: { conferenceSolutionKey: { type: "hangoutsMeet" }, requestId: r },
		},
		reminders: {
			useDefault: false,
			overrides: [
				{ method: "email", minutes: 24 * 60 },
				{ method: "popup", minutes: 15 },
			],
		},
		visibility: "public",
	};

	ApiCalendar.createEvent(options, CALENDAR_ID, { conferenceDataVersion: 1 })
		.then((result) => console.log(result))
		.catch((error) => {
			console.log(error);
		});
}

Is it possible to use listUpcomingEvents function from a different page/component

When I call listUpcomingEvents from the same component in my app that I actioned the handleAuthClick method it works, but when I attempt to call this function from another page it tells me 'this.gapi is not loaded" & that the listUpcomingEvents is not a function?

Is there a way to authenticate from one component/page in my app and call listUpcomingEvents from a different one?

Just to provide some context I am working with create-react-app using react-router 4

Thank you very much,
Marco

Authentication Callback

Please add call back for authentication.

Ex:
ApiCalendar.handleAuthClick()
.then((result) => {
console.log(result);
}).catch((error) => {
console.log(error);
});

Listing past events

Hello,
How would I go about listing past events from a calendar?
Best wishes,
George.

Add users to event.

First of all, this is just great! Thank you so much.

It would be great to have the opportunity to add users (invite them) to events. Im using this to schedule meetings with people.
Thanks in advance.

How do you pass in optional query parameters like sendUpdates?

hi, as per the docs https://developers.google.com/calendar/v3/reference/events/insert
in order to notify the guests through email, you can use the sendUpdates parameter.

How does one pass that in react-google-calendar-api ?

The invitees are not receiving an email at the moment.

You can see an example here https://developers.google.com/calendar/v3/reference/events/insert?apix=true#try-it

I tried passing the event as the following with appropriate values for start and end time ( NOT empty as shown below )

{
      "sendUpdates": "all",
      "resource": {
        "end": {},
        "start": {}
      }
}

but that gave a 400 error saying 'end time not found'

If I just pass an object like

var event = {
   'start' : {},
   'end' : {}
}

Again, with appropriate values of start and end time with datetime and timezone, it works

What am i missing?

List upcoming Events

I'm trying to list the upcoming events like so

  const GetCalenderEvents = async () => {
    const response = await fetch(ApiCalendar.listUpcomingEvents(10));
    console.log(response);
  };

But the response I'm getting is from http://localhost:3000/[object%20Object] I'm using React and Javascript and the documentation from the read me seems to be using typescript.
How would I make the request or get the calendar data?

HTTP Error Code 401

Upon signing in, the popup gets closed by itself and displays: "dipframe_initialization_failed"

I am using your latest package version and OAuth credentials generated by a Google console project of mine as well as

script="https://apis.google.com/js/platform?onload=init" async defer

Kindly advise on making authentication smoother.

handleAuthClick should return promise

Hello!

this.gapi.auth2.getAuthInstance().signIn() returns a promise (Docs here)

and it would be great to have that reflected in the handleAuthClick method :)

I can make a quick PR if helpful

can't find apiGoogleconfig.json in ubuntu server

ERROR` in ../~/react-google-calendar-api/build/ApiCalendar.js
Module not found: Error: Can't resolve '../../apiGoogleconfig.json' in '/var/www/staging/development/source/node_modules/react-google-calendar-api/build'
 @ ../~/react-google-calendar-api/build/ApiCalendar.js 11:13-50
 @ ./src/components/Nanny/NannyProfile.js
 @ ./src/routes/index.js
 @ ./src/index.js

It think, it will be better if we set config by importing.
Automated resolving config might be problem.

I found some issue...
In my local windows machine, your package didn't build and run directly.
Btw in the ubuntu server node_modules/react-google-calendar-api/ I found ./build directory, so that your built package didn't know config json file path since directory level is changed.

Thanks in advance

Using an arrow function into handleClientLoad() method cause to use wrong scope

I've noticed that the handleClientLoad method uses an arrow function to init the client.

script.onload = () => {
   window['gapi'].load('client:auth2', this.initClient);
};

This causes that the this scope used here is related to the arrow function, not the whole class, because of the arrow function behavior.

You can fix it switching to ES5 functions:

script.onload = function () {
   window['gapi'].load('client:auth2', this.initClient);
};

handleAuthClick() returns undefined

I am using this package to integrate google calendar into one of my project and when I call ApiCalendar.handleAuthClick() and try to see the response it gives me undefined.

Here is the code I am doing right now:
ApiCalendar.handleAuthClick().then((response) => { console.log(response); })

Seems like it does not send promise as a response if that is the case then how can I get the access token?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.