首页  >  问答  >  正文

使用fetch在React JS中创建日历事件的JavaScript方法

在 React JS 应用程序中,我想创建一个谷歌日历事件。我完全不熟悉 google api,我正在尝试学习/弄清楚如何做到这一点。

以下是一个反应测试组件,它显示一个带有“google登录”按钮和“添加到日历”按钮的空白屏幕。

我为此示例创建了一个 TEST_EVENT 常量。

用户必须先登录,然后单击“添加到日历”按钮。我确实获得了访问令牌 - 下一步是创建事件。我的问题是,如果我有 access_token,如何使用 fetch API 创建日历事件?

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

P粉222320176P粉222320176228 天前405

全部回复(1)我来回复

  • P粉470645222

    P粉4706452222024-03-28 00:54:40

    感谢我在 youtube 上观看的 3 个由 Coopercodes 制作的视频,我在下面有了一个工作示例。此示例使用隐式流在 Google 日历上创建一个事件。我花了几天时间才让它发挥作用。我希望这对其他人有帮助:

    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 (
    
            
    {Object.keys(user).length != 0 && } {user &&

    {user.name}

    }
    ) } export default TestGIS

    回复
    0
  • 取消回复