I am making this Google authentication component which uses google OAuth API https://apis.google.com/js/api.js. I have embedded this inside script tag in index.html file in the React app.
All methods of this API are accessed with window method inside the app.
I am facing issue with sign in and sign out button that I have placed in the return statement. I am not able to access the auth object outside the scope.
How can I access the auth object to be used for sign in /sign out buttons.
import React, { useEffect, useState } from "react";
const GoogleAuth = () => {
const [isSignedIn, setIsSignedIn] = useState(null);
useEffect(() => {
window.gapi.load("client:auth2", () => {
window.gapi.client
.init({
clientId:
"888522435394-63o2fafiofkj70c7t8m7lurf7qr9q3cv.apps.googleusercontent.com",
scope: "email",
plugin_name: "streamy",
})
.then(() => {
const auth = window.gapi.auth2.getAuthInstance(); //VARIABLE DECLARED HERE!!
setIsSignedIn(auth.isSignedIn.get());
auth.isSignedIn.listen(() => {
setIsSignedIn(auth.isSignedIn.get());
});
});
});
}, []);
if (isSignedIn === null) {
return null;
} else if (isSignedIn) {
return (
<button className="ui red google button" onClick={() =>{auth.signOut()}}> // ERROR ACCESSING THIS!!
<i className="google icon" />
Sign out
</button>
);
}
return (
<button className="ui red google button" onClick={() =>{auth.signOut()}}> // ERROR ACCESSING THIS!!
<i className="google icon" />
Sign in
</button>
);
};
export default GoogleAuth;