javascriptreactjsgoogle-signingoogle-identitygoogle-one-tap

how to define variable google when using google one tap javascript API


I am following this documentation google one tap sign in to implement google one tap sign-in in my react app.

I have added below code to my component JSX and I started to have google prompt to sign-in:

  const handleCredentialResponse = response => {
    console.log('response', response);
  };

return (
    <Fragment>
      <div
        id="g_id_onload"
        data-auto_select = 'false'
        data-client_id={clientId}
        data-callback={(e) => handleCredentialResponse(e)}>
      </div>
    </Fragment>
  );

Prooblem I am facing is that callback function is not triggering. After looking for a solution I stumbled upon this SO question. Where the OP has asked the similar question, and used javascript API syntax to show google one tap instead of HTML code To follow above question I read this documentation Use the One Tap JavaScript API. But I am not able to understand that from where does the variable google is coming from?

Sample code:

window.onload = function () {
    google.accounts.id.initialize({
      client_id: 'YOUR_GOOGLE_CLIENT_ID',
      callback: handleCredentialResponse
    });
    google.accounts.id.prompt();
  }

If someone could tell me that might solve my problem of a callback function not triggering. Thanks!


Solution

  • I have found a solution with help of comment posted by Nilesh Patel and this package react-google-one-tap-login.

    Checking the source code in the above package I manage to find out that I have to

    replace:

     google.accounts.id.initialize({
        client_id: CLIENT_ID,
        callback: data => handleCredentialResponse(data),
        state_cookie_domain: 'https://example.com',
      });
    

    with

     window.google.accounts.id.initialize({
        client_id: CLIENT_ID,
        callback: data => handleCredentialResponse(data),
        state_cookie_domain: 'https://example.com',
      });