Home > Software engineering >  React throws error when trying to load Google Sign-In but only for the first load
React throws error when trying to load Google Sign-In but only for the first load

Time:11-27

import { useEffect } from "react";
import jwtDecode from "jwt-decode";
import { useDispatch } from "react-redux";
import { login } from "../redux/user";
import { setCurrentPath } from "../redux/currentpath";

const Login = () => {
  const dispatch = useDispatch();
  const google = window.google;

  function handleCallbackResponse(response) {
    var user = jwtDecode(response.credential);
    dispatch(login({ name: user.name, avatar: user.picture }));
  };

  useEffect(() => {
    dispatch(setCurrentPath(window.location.pathname));
  }, []);

  useEffect(() => {
    /* global google */
    google.accounts.id.initialize({
      client_id: '650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com',
      callback: handleCallbackResponse
    });

    google.accounts.id.renderButton(
      document.getElementById('signInDiv'),
      { theme: 'outline', size: 'large' }
    );
  }, []);
  
  return (
    <div className="content login">
      <div className='greeting-text'>
        <h1>Welcome to <br className="br" /> Cat Room!</h1>
        <p>Here you can talk about some very interesting topics, like milk, yarn balls, mice and many more. So don't be shy, come and join us! You can log in with Google right below this pharagraph.</p>
      </div>
      <div id="signInDiv">
      </div>
    </div>
  );
};
 
export default Login;

When I try to load it for first time it throws this error: Uncaught TypeError: google is undefined

and points to this line: google.accounts.id.initialize({

If I reload the page it works again. But if I clear browser history and load this page again it throws the same error. Then if I reload it suddenly works...

I tried adding google as a dependency to the UseEffect hook where the error uccors. Then the same thing happened but this time it threw an error that said: n is undefined.

I have no idea what could be the problem and I would greatly appreciate if somebody could help because I need it for my portfolio and it's quite important to work flawlessly. Thanks in advance!

UPDATE:

My mistake! n is undefined only occurs if I load the page in github pages. For which I had to change the basename from "/cat-room" to "/cat-room/". Literally this is the only difference between the local and the github pages version. Not sure if it's important but I felt like I should note it.

Either way on both versions the same thing happens. For first load throws error. Then I reload and works flawlessly.

CodePudding user response:

useEffect(() => {
    if(window.google){
        /* global google */
        window.google.accounts.id.initialize({
          client_id: '650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com',
          callback: handleCallbackResponse
        });
    
        window.google.accounts.id.renderButton(
          document.getElementById('signInDiv'),
          { theme: 'outline', size: 'large' }
        );
    }
 }, [window.google]);

CodePudding user response:

I could solve it finally. I'm gonna put it out here if anyone needs it in the future. Use this plugin: @react-oauth/google

My code looks like this:

Login Component:

import { useEffect } from "react";
import jwtDecode from "jwt-decode";
import { useDispatch } from "react-redux";
import { login } from "../redux/user";
import { setCurrentPath } from "../redux/currentpath";
import { GoogleLogin } from '@react-oauth/google';

const Login = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(setCurrentPath(window.location.pathname));
  }, []);
  
  /* const google = window.google;

  function handleCallbackResponse(response) {
    var user = jwtDecode(response.credential);
    dispatch(login({ name: user.name, avatar: user.picture }));
  };

  useEffect(() => { */
    /* global google */
    /* google.accounts.id.initialize({
      client_id: '650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com',
      callback: handleCallbackResponse
    });

    google.accounts.id.renderButton(
      document.getElementById('signInDiv'),
      { theme: 'outline', size: 'large' }
    );
  }, []); */
  
  return (
    <div className="content login">
      <div className='greeting-text'>
        <h1>Welcome to <br className="br" /> Cat Room!</h1>
        <p>Here you can talk about some very interesting topics, like milk, yarn balls, mice and many more. So don't be shy, come and join us! You can log in with Google right below this pharagraph.</p>
      </div>
      <div id="signInDiv">
        <GoogleLogin
          onSuccess={credentialResponse => {
            console.log(credentialResponse.credential);
            var user = jwtDecode(credentialResponse.credential);
            dispatch(login({ name: user.name, avatar: user.picture }));
          }}
          one rror={() => {
            console.log('Login Failed');
          }}
        />
      </div>
      {/* <div id="signInDiv">
      </div> */}
    </div>
  );
};
 
export default Login;

index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import store from './redux/store';
import { Provider } from 'react-redux';
import { GoogleOAuthProvider } from '@react-oauth/google';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <GoogleOAuthProvider clientId="650598283556-4tl875cetd7ueallsq486darhpj5e30n.apps.googleusercontent.com"><App /></GoogleOAuthProvider>
    </Provider>
  </React.StrictMode>
);
  • Related