Is it possible to create a react app that syncs events from a google calendar?

30 views Asked by At

i want to create a react app that displays events from a calendar that i own. I don't want a user to have to log in to their google account when they visit this website i only want them to see the events from my calendar. This is my code:

"use client"
import React, { useEffect, useState } from 'react';

const Schedule = () => {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    const loadGoogleAPIs = async () => {
      const gapiScript = document.createElement('script');
      gapiScript.src = 'https://apis.google.com/js/api.js';
      gapiScript.async = true;
      gapiScript.defer = true;
      gapiScript.onload = initGapi;
      document.body.appendChild(gapiScript);
    };

    const initGapi = () => {
      window.gapi.load('client:auth2', initClient);
    };

    const initClient = async () => {
      try {
        await window.gapi.client.init({
          apiKey: process.env.GOOGLE_API_KEY,
          clientId: process.env.GOOGLE_CLIENT_ID,
          discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
          scope: 'https://www.googleapis.com/auth/calendar.readonly',
        });
        // Check if user is already signed in
        const isSignedIn = window.gapi.auth2.getAuthInstance().isSignedIn.get();
        if (isSignedIn) {
          listUpcomingEvents();
        }
      } catch (error) {
        console.error('Error initializing client:', error);
      }
    };

    const listUpcomingEvents = async () => {
      try {
        const response = await window.gapi.client.calendar.events.list({
          'calendarId': 'primary',
          'timeMin': (new Date()).toISOString(),
          'showDeleted': false,
          'singleEvents': true,
          'maxResults': 10,
          'orderBy': 'startTime',
        });
        const fetchedEvents = response.result.items;
        setEvents(fetchedEvents);
      } catch (error) {
        console.error('Error fetching events:', error);
      }
    };

    loadGoogleAPIs();

    // Clean up function to remove the dynamically added script
    return () => {
      const script = document.querySelector('script[src="https://apis.google.com/js/api.js"]');
      if (script) {
        document.body.removeChild(script);
      }
    };
  }, []);

  return (
    <div>
      <h2>Calendar Events</h2>
      <div>
        {events.length > 0 ? (
          <ul>
            {events.map((event, index) => (
              <li key={index}>
                {event.summary} ({event.start.dateTime || event.start.date})
              </li>
            ))}
          </ul>
        ) : (
          <p>No events found.</p>
        )}
      </div>
    </div>
  );
};

export default Schedule;





I get the following error:

client_id and scope must both be provided to initialize OAuth. TypeError: null is not an object (evaluating 'window.gapi.auth2.getAuthInstance

0

There are 0 answers