Search code examples
javascriptreactjsgoogle-oauth

Google Auth in React


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);
            });
        });
    });
  }

Screenshoot


Solution

  • 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.