Reputation: 33
I get the following error (in below screenshot) when I implemented google auth in react.
TypeError: window.gapi.init is not a function
(anonymous function)
src/components/GoogleAuth.js:8
5 | class GoogleAuth extends Component {
6 | componentDidMount() {
7 | window.gapi.load("client:auth2", () => {
> 8 | window.gapi
9 | .init({
10 | clientId:
11 | "258474052449-
Code:
componentDidMount() {
window.gapi.load("client:auth2", () => {
window.gapi
.init({
clientId:
"258474052449-vs1334g29cemopfhplff5nqe5l2vshac.apps.googleusercontent.com",
scope: "email"
})
.then(() => {
window.gapi.client
.request({
path:
"https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names"
})
.then(() => {
this.auth = window.gapi.auth2.getAuthInstance();
this.onAuthChange(this.auth.isSignedIn.get());
this.auth.isSignedIn.listen(this.onAuthChange);
});
});
});
}
Upvotes: 3
Views: 821
Reputation: 1
First, you need to add this script in html file of react:
<script src="https://accounts.google.com/gsi/client" async defer></script>,
{ useEffect, useRef } from 'react';
import swal from 'sweetalert';
const Logingoogle = () => {
const buttonContainerRef = useRef(null);
useEffect(() => {
const handleCredentialResponse = (response) => {
console.log(response.credential);
};
const initGoogleSignIn = () => {
if (window.google?.accounts?.id) {
window.google.accounts.id.initialize({
client_id: "Your Client ID",
callback: handleCredentialResponse
});
if (buttonContainerRef.current) {
window.google.accounts.id.renderButton(
buttonContainerRef.current,
{ theme: "outline", size: "large" }
);
}
} else {
setTimeout(initGoogleSignIn, 500);
}
};
initGoogleSignIn();
}, []);
return (
<div>
<div ref={buttonContainerRef}></div>
</div>
);
};
export default Logingoogle;
Upvotes: 0
Reputation: 2755
The Google API docs show that the init
function is defined on the client
object.
Your window.gapi.init
should be window.gapi.client.init
.
Upvotes: 4