Kubessandra / react-google-calendar-api

An api to manage your google calendar

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

gapi is not defined

Faurby opened this issue · comments

I am using Next.js. I have tried to read an earlier issue, and use the onLoad function, but just calling throws and error.
I have and API KEY and an OAUTH Client ID. Help pls :)

I have this basic code:

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

export default function Home() {
  const clientID = process.env.REACT_APP_CLIENT_ID;
  const apiKey = process.env.REACT_APP_CALENDAR_API_KEY;
  const calendarID = process.env.REACT_APP_CALENDAR_ID;

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

  const apiCalendar = new ApiCalendar(config);

  apiCalendar.onLoad(() => {
    apiCalendar.handleAuthClick(); // Example on how to trigger auth manually
    apiCalendar
      .listUpcomingEvents(10, calendarID)
      .then((res: { result: { items: any } }) => {
        console.log(res.result.items);
      });
  });

  return apiCalendar
    .listUpcomingEvents(10, calendarID)
    .then((res: { result: { items: any } }) => {
      console.log(res.result.items);
    });
}

and I get the following error:

billede

Hey,
If you log in your "onLoad" is there anything or throwing before ?
Also can you check the network and see if the gapi script is well fetched

Next.js, I'm getting the same error and here are the network calls
image

Oh you are in nextjs, your component is having
'use client' in the top ?

Having the same issue on React.js. I have a button in my component that handles sign in and adding a sample event to a user's google calendar. Here is my code:

const config = {
            clientId: clientId,
            apiKey: apiKey,
            scope: SCOPES,
            discoveryDocs: DISCOVERY_DOCS,
        };
const apiCalendar = new ApiCalendar(config);
await apiCalendar.handleAuthClick()
const event = {
    'summary': 'test event',
    'start': {
        'dateTime': getNextDayOfTheWeekWithTime(day,startTime) // function to change something like "Saturday 2pm" to ISO time,
        'timeZone': 'America/Los_Angeles'
    },
    'end': {
        'dateTime': getNextDayOfTheWeekWithTime(day,endTime) // // function to something like change "Saturday 2pm" to ISO time,
        'timeZone': 'America/Los_Angeles'
    }
}
apiCalendar.createEvent(event)
.then((result) => {
    console.log(result);
})

When I run my application, nothing happens when I click the button, but I get this in console:

Screenshot 2023-12-23 at 1 36 02 PM

Since it is saying this.gapi is not loaded, I have tried using the onLoad function like this:

const config = {
    clientId: clientId,
    apiKey: apiKey,
    scope: SCOPES,
    discoveryDocs: DISCOVERY_DOCS,
};
const apiCalendar = new ApiCalendar(config);
apiCalendar.onLoad(async () => {
    await apiCalendar.handleAuthClick()
    const event = {
        'summary': 'test event',
        'start': {
            'dateTime': getNextDayOfTheWeekWithTime(day,startTime) // function to change something like "Saturday 2pm" to ISO time,
            'timeZone': 'America/Los_Angeles'
        },
        'end': {
            'dateTime': getNextDayOfTheWeekWithTime(day,endTime) // // function to something like change "Saturday 2pm" to ISO time,
            'timeZone': 'America/Los_Angeles'
        }
    }
    apiCalendar.createEvent(event)
    .then((result) => {
        console.log(result);
    })
})

I am still getting the same exact error. Any help would be appreciated.

Facing a similar issue

Hey,
If on nextjs are you using use client on top of the files ?

Same issue on a react project, any updates?

Which framework are you using all ?

same issue in nextjs and i'm use 'use client' in the top of my file

Ok I probably have found the issue:
To work gapi need to be loaded this is loaded when we create the ApiCalendar

So before using any method of ApiCalendar you need to make sure that this is Loaded.
For example using it in the onLoad method or creating a state(apiCalendarReady)

EX:

  const clientID = process.env.REACT_APP_CLIENT_ID;
  const apiKey = process.env.REACT_APP_CALENDAR_API_KEY;
  const calendarID = process.env.REACT_APP_CALENDAR_ID;
  const [apiCalendarReady, setApiCalendarReady] = useState(false)

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

  const apiCalendar = new ApiCalendar(config);

  apiCalendar.onLoad(() => {
    apiCalendar.handleAuthClick(); // Example on how to trigger auth manually
    apiCalendar
      .listUpcomingEvents(10, calendarID)
      .then((res: { result: { items: any } }) => {
        console.log(res.result.items);
      });
    setApiCalendarReady(true)
  });

  if (apiCalendarReady) {
    return apiCalendar
      .listUpcomingEvents(10, calendarID)
      .then((res: { result: { items: any } }) => {
        console.log(res.result.items);
      });
  }
  return null

@Kubessandra not work.

Do you have some code example ?
And when you say does not work, what is the issue, error or nothing happening ?

Maybe this "ugly" workout will help with "gapi is not defined":

    <script type="text/javascript">
      let tokenClient;
      let gapiInited = false;
      let gisInited = false;

      /**
       * Callback after api.js is loaded.
       */
      function gapiLoaded() {
        gapi.load("client", initializeGapiClient);
      }

      /**
       * Callback after the API client is loaded. Loads the
       * discovery doc to initialize the API.
       */
      async function initializeGapiClient() {
        gapiInited = true;
      }

      /**
       * Callback after Google Identity Services are loaded.
       */
      function gisLoaded() {
        gisInited = true;
      }
    </script>
    <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
    <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>

Place that code above your main scripts.

Maybe this "ugly" workout will help with "gapi is not defined":

    <script type="text/javascript">
      let tokenClient;
      let gapiInited = false;
      let gisInited = false;

      /**
       * Callback after api.js is loaded.
       */
      function gapiLoaded() {
        gapi.load("client", initializeGapiClient);
      }

      /**
       * Callback after the API client is loaded. Loads the
       * discovery doc to initialize the API.
       */
      async function initializeGapiClient() {
        gapiInited = true;
      }

      /**
       * Callback after Google Identity Services are loaded.
       */
      function gisLoaded() {
        gisInited = true;
      }
    </script>
    <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
    <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>

Place that code above your main scripts.

@OchotaDariusz this package is injecting the script already in the page, but yes what you are suggesting can make it work but the package should be the one doing it

スクリーンショット 2024-02-19 2 42 16

The onLoad does not work in the first place.

And with the solution of @OchotaDariusz ?