Unable to delete an event using Google Calendar API on React

498 views Asked by At

I am trying to create a simple schedule management app using React and HAsura GraphQL API and I am trying to integrate it with my Google Calendar. However I am unable to delete the required event. This is my first time working with Google API so I am a not sure if my syntax is a problem or there is some other mistake that I am making. It would be great if you could explain what my mistake was so that I can make sure not to do the same mistake in the future.

Here is my code:

import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Grid } from '@material-ui/core';
import DeleteIcon from '@material-ui/icons/Delete';
import IconButton from '@material-ui/core/IconButton';
import { makeStyles } from '@material-ui/core/styles';
import { gql } from "@apollo/client";
import { useMutation } from "@apollo/client";
import { GET_MY_SCHEDULE } from './currentscheduledisplay';
import EditRoundedIcon from '@material-ui/icons/EditRounded';
import { Icon } from 'semantic-ui-react'


const useStyles = makeStyles((theme) => ({
    margin: {
      margin: theme.spacing(1),
    },
    extendedIcon: {
      marginRight: theme.spacing(1),
    },
  }));


function Schedule(props) {

    const [ hover, setHover ] = useState(false);

    const REMOVE_TODO = gql`
    mutation removeSchedule ($id: Int!) {
      delete_Schedule(where: {id: {_eq: $id}}) {
        affected_rows
      }
    }
  `;
  
  const [removeTodoMutation] = useMutation(REMOVE_TODO);
  
  function deleteSchedule(scheduleId)
  {
      removeTodoMutation({
          variables: {id: scheduleId},
          optimisticResponse: true,
          update: (cache) => {
            const existingSchedule = cache.readQuery({ query: GET_MY_SCHEDULE });
            const newSchedule = existingSchedule.Schedule.filter(t => (t.id !== scheduleId));
            cache.writeQuery({
              query: GET_MY_SCHEDULE,
              data: {Schedule: newSchedule}
            });
          }
        });

        var gapi = window.gapi
        var CLIENT_ID = "_____Client ID_______"
        var API_KEY = "________Api Key_______________"
        var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"]
        var SCOPES = "https://www.googleapis.com/auth/calendar.events"

        var toBeDeleteEventId = ""

        gapi.load('client:auth2', () => {
          console.log('Client has been loaded')
    
          gapi.client.init({
            apiKey: API_KEY,
            clientId: CLIENT_ID,
            discoveryDocs: DISCOVERY_DOCS,
            scope: SCOPES,
          })

          gapi.auth2.getAuthInstance().signIn().then(() => {

            gapi.client.calendar.events.list({
              'calendarId': 'primary',
              'timeMin': (new Date()).toISOString(),
              'showDeleted': false,
              'singleEvents': true,
              'maxResults': 100,
              'orderBy': 'startTime'
            }).then(response => {
              const events = response.result.items
              console.log("EVENTS", events)
              for(let i = 0; i < events.length; i++) {
                if(events.summary === props.title) {
                  toBeDeleteEventId = events.id
                  console.log("Delete ID is as follows: ", toBeDeleteEventId)
                }

              }
            })

            var request = gapi.client.calendar.events.delete({
              'calendarId': 'primary',
              'eventId': toBeDeleteEventId
            })
            request.execute(event => {
              console.log("Delete request ",event)
            });
          })
      })
  }
  





    var monthNum = props.date[5] + props.date[6];
    var dateWords = props.date[8] + props.date[9];
    var month = "";

    switch(monthNum) {
        case "1": 
             month = "Jan";
             break;
        case "2": 
            month = "Feb"
            break;
            case "2": 
            month = "Feb"
            break;
        case "3": 
            month = "Mar"
            break;
        case "4": 
            month = "Apr"
            break;        
        case "5": 
            month = "May"
            break;        
        case "6": 
            month = "Jun"
            break;        
        case "7": 
            month = "Jul"
            break;        
        case "8": 
            month = "Aug"
            break;        
        case "9": 
            month = "Sept"
            break;        
        case "10": 
            month = "Oct"
            break;        
        case "11": 
            month = "Nov"
            break;
        case "12": 
            month = "Dec"
            break;
    }
    dateWords = month + " " + dateWords;


    const actualStartTime = props.startTime.substring(0, 5);
    const actualEndTime = props.endTime.substring(0, 5);
    console.log("Time  = ", props.startTime)
    const classes = useStyles();
    
    return (
      <div className="schedule" onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)} >
          <Grid container spacing={5} xs={12} >
              <Grid item xs={3}>
                <div className="date">
                    {/* {props.date} */}
                    {dateWords}
                </div>
              </Grid>
              <Grid item xs={7}>
                  <div className="details">
                    <div className="title">
                        <h4>{props.title}</h4>
                    </div>

                    <div className="time">
                        {actualStartTime} to {actualEndTime}
                    </div>

                    <div className="participants">
                        Participants : {props.participants}
                    </div>
                </div>

                {/* <CloseIcon /> */}
              </Grid>

              <Grid item xs={2}>
                <div className="delete-button">
                    <IconButton aria-label="edit" className={classes.margin} onClick={() => deleteSchedule(props.id)} style={{color: hover ? "white" : "#007bff", display: 'inline'}}  >
                        <EditRoundedIcon />
                    </IconButton>
                    <IconButton aria-label="delete" className={classes.margin} onClick={() => deleteSchedule(props.id)} style={{color: hover ? "white" : "#007bff", display: 'inline'}}  >
                        <DeleteIcon />
                    </IconButton>
                </div>
              </Grid>

          </Grid>
        
      </div>
    );
}

export default Schedule;
0

There are 0 answers