0

In a React JS app I want to create a google calendar event. I am completely unfamiliar with google apis and am trying to learn / figure out how to do this.

the following is a react test component that displays a blank screen with a "google login" button and an "add to calendar" button.

I've created a TEST_EVENT const for this example.

User has to login first and then click the "add to calendar" button. I do get an access token - next step is to create the event. My question is how can I create the calendar event with fetch API given I have an access_token?

import React, { useEffect, useState } from 'react'
import jwt_decode from "jwt-decode";

const CLIENT_ID = '25262567698-tsaoo718sc35n3k25os074b17jklc5rm.apps.googleusercontent.com';
const SCOPES = 'https://www.googleapis.com/auth/calendar';

const TEST_EVENT = {
    'summary': 'Example Event',
    'location': 'New York, NY',
    'description': 'a description for this',
    'start': {
        'dateTime': '2023-03-26T10:00:00-04:00',
        'timeZone': 'America/New_York',
    },
    'end': {
        'dateTime': '2023-03-26T11:00:00-04:00',
        'timeZone': 'America/New_York',
    },
};

const TestGIS = (props) => {


    const [user, setUser] = useState({});
    const [tokenClient, setTokenClient] = useState({});

    function handleCallbackResponse(response) {
        console.log('encoded JWT ID token:' + response.credential);
        var userObject = jwt_decode(response.credential);
        console.log(userObject)
        setUser(userObject);
        document.getElementById('signInDiv').hidden = true;
    }

    function handleSignOut(event) {
        setUser({});
        document.getElementById('signInDiv').hidden = false;
    }



    useEffect(() => {

        /* global google */
        const google = window.google;
        google.accounts.id.initialize({
            client_id: CLIENT_ID,
            callback: handleCallbackResponse
        })
        google.accounts.id.renderButton(
            document.getElementById('signInDiv'),
            { theme: 'outline', size: 'large' }
        );

        // google.accounts.id.prompt(); // this is added to popup the login dialog when page is first loaded - didn't work

        // Get Access Token
        // create something called a tokenClient
        setTokenClient(
            google.accounts.oauth2.initTokenClient({
                client_id: CLIENT_ID,
                scope: SCOPES,
                callback: (tokenResponse) => {
                    console.log('tokenResponse=', tokenResponse);
                    // we now have access to a live token to use for ANY google API
                    if (tokenResponse && tokenResponse.access_token) {
                        // create the calendar event here

                    }
                }
            })
        );



    }, []);


    function createCalendarEvent() {
        tokenClient.requestAccessToken();
    }




    
    //-----------------------------------------------------------------
    return (

        <div className='main-cover' style={{ backgroundColor: 'lightblue', width: '100%', height: '100%', zIndex: '10000' }}   >

            <div id="signInDiv"></div>
            {Object.keys(user).length != 0 &&
                <button onClick={(e) => handleSignOut(e)}>Sign Out</button>
            }

            {user &&
                <div>
                    <img src={user['picture']}></img>
                    <h3>{user.name}</h3>
                    <button onClick={() => createCalendarEvent()}>Create calendar event</button>
                </div>
            }

        </div>


    )
}
export default TestGIS 

2
  • In your script, what is gapi? From your script, I'm worried that you might misunderstand googleapis for Javascript and Node.js. But, I cannot know your actual situation. So, I cannot propose a clear answer. I apologize for this. Commented Mar 25, 2023 at 1:20
  • I finally got a working version, shown in the answer below. Is there a better, simpler way to do this? Commented Mar 25, 2023 at 15:34

1 Answer 1

0

Thanks to the 3 videos I watched on youtube by coopercodes, I have a working example below. This example creates an event on google calendar using the implicit flow. I spent a couple of days to get this working. I hope this helps someone else:


import React, { useEffect, useState } from 'react'
import jwt_decode from "jwt-decode";

const CLIENT_ID = '25262567698-tsaoo718sc35n3k25os074b17jklc5rm.apps.googleusercontent.com';
const SCOPES = 'https://www.googleapis.com/auth/calendar';

const TEST_EVENT = {
    'summary': 'Example Event',
    'location': 'New York, NY',
    'description': 'a description for this',
    'start': {
        'dateTime': '2023-03-26T10:00:00-04:00',
        'timeZone': 'America/New_York',
    },
    'end': {
        'dateTime': '2023-03-26T11:00:00-04:00',
        'timeZone': 'America/New_York',
    },
};

const TestGIS = (props) => {


    const [user, setUser] = useState({});
    const [tokenClient, setTokenClient] = useState({});

    function handleCallbackResponse(response) {
        console.log('encoded JWT ID token:' + response.credential);
        var userObject = jwt_decode(response.credential);
        console.log(userObject)
        setUser(userObject);
        document.getElementById('signInDiv').hidden = true;
    }

    function handleSignOut(event) {
        setUser({});
        document.getElementById('signInDiv').hidden = false;
    }

    useEffect(() => {

        /* global google */
        const google = window.google;
        google.accounts.id.initialize({
            client_id: CLIENT_ID,
            callback: handleCallbackResponse
        })
        google.accounts.id.renderButton(
            document.getElementById('signInDiv'),
            { theme: 'outline', size: 'large' }
        );


        // Get Access Token
        // create something called a tokenClient
        setTokenClient(
            google.accounts.oauth2.initTokenClient({
                client_id: CLIENT_ID,
                scope: SCOPES,
                callback: (tokenResponse) => {
                    console.log('tokenResponse=', tokenResponse);
                    // we now have access to a live token to use for ANY google API
                    if (tokenResponse && tokenResponse.access_token) {
                        // create the calendar event here

                        fetch ('https://www.googleapis.com/calendar/v3/calendars/primary/events',{
                            method: 'POST',
                            headers: {
                                'Authorization':'Bearer '+tokenResponse.access_token
                            },
                            body:JSON.stringify(TEST_EVENT)
                        }).then((data) => {
                            return data.json();
                        }).then((data) => {
                            console.log(data);
                            alert('event created check google calendar')
                        })  

                    }
                }
            })
        );



    }, []);


    function createCalendarEvent() {
        tokenClient.requestAccessToken();
    }




    //---------------------------------------------------------

   
    return (

        <div className='main-cover' style={{ backgroundColor: 'lightblue', width: '100%', height: '100%', zIndex: '10000' }}   >

            <div id="signInDiv"></div>
            {Object.keys(user).length != 0 &&
                <button onClick={(e) => handleSignOut(e)}>Sign Out</button>
            }

            {user &&
                <div>
                    <img src={user['picture']}></img>
                    <h3>{user.name}</h3>
                    <button onClick={() => createCalendarEvent()}>Create calendar event</button>
                </div>
            }

        </div>


    )
}
export default TestGIS


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.