I'm developing a react calendar app where a user can see their events retrieved from a Google calendar or add their own ones through the app.
I am using @react-oauth/google
to sign in and get credentials.
Here I can get a clientId
and credential
. How can I use them to add/retrieve events to/from a Google Calendar? Should I add credentials to a request object somehow? (NOTE: instead of "" in CLIENT_ID
and API_KEY
I inserted some valid values that I got here https://console.cloud.google.com/. Authorized JavaScript origins are http://localhost:3000 and http://localhost)
error: {code: 401, data: Array(1), message: 'Request is missing required authentication credent…ogle.com/identity/sign-in/web/devconsole-project.'}
import React from "react";
import { GoogleOAuthProvider, GoogleLogin } from "@react-oauth/google";
const GoogleCalendar = () => {
var gapi = window.gapi;
var CLIENT_ID =
"";
var DISCOVERY_DOCS = [
"https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest",
];
var SCOPES = "https://www.googleapis.com/auth/calendar.events";
var API_KEY = "";
const AddEvent = (credentialResponse) => {
var event = {
summary: "Google I/O 2015",
location: "800 Howard St., San Francisco, CA 94103",
description: "A chance to hear more about Google's developer products.",
start: {
dateTime: "2022-05-21T09:00:00-07:00",
timeZone: "America/Los_Angeles",
},
end: {
dateTime: "2022-05-21T17:00:00-07:00",
timeZone: "America/Los_Angeles",
},
recurrence: ["RRULE:FREQ=DAILY;COUNT=2"],
attendees: [
{ email: "[email protected]" },
{ email: "[email protected]" },
],
reminders: {
useDefault: false,
overrides: [
{ method: "email", minutes: 24 * 60 },
{ method: "popup", minutes: 10 },
],
},
};
gapi.client.load("calendar", "v3", () => console.log("bam!"));
var request = gapi.client.calendar.events.insert({
calendarId: "primary",
resource: event,
});
request.execute((event) => {
console.log(event);
window.open(event.htmlLink);
});
};
return (
<>
<GoogleOAuthProvider clientId={CLIENT_ID}>
<GoogleLogin
onSuccess={(credentialResponse) => {
console.log(credentialResponse);
AddEvent(credentialResponse);
}}
one rror={() => {
console.log("Login Failed");
}}
/>
</GoogleOAuthProvider>
</>
);
};
export default GoogleCalendar;
CodePudding user response:
In order to add the events, the client should be loaded and signed in before calling add events. What you did is correct but you have to wait for the response of client load then you can call add events:
gapi.client.setApiKey('YOUR_API_KEY');
gapi.client
.load('https://content.googleapis.com/discovery/v1/apis/calendar/v3/rest')
.then((res) => {
var request = gapi.client.calendar.events.insert({
calendarId: 'primary',
resource: event,
});
request.execute((event) => {
console.log(event);
window.open(event.htmlLink);
});
});
CodePudding user response:
you need your access_token to authorize to google APIs, you can get it from using Authorization flows from @react-oauth/google by using useGoogleLogin