GoogleAuth hooks

Sign-in & sign-out react hooks for google-auth
import {useState} from 'react';
import {GoogleLoginResponse, useGoogleLogin} from 'react-google-login';

const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID as string;

type CallbackFunction = (token) => void;

type UseGoogleSignInReturn = {
  googleSignIn: CallbackFunction;
  error: boolean;
};

export function useGoogleSignIn(
  onSignIn: CallbackFunction
): UseGoogleSignInReturn {
  const [hasError, setHasError] = useState(false);

  function handleOnSuccess({tokenId}: GoogleLoginResponse) {
    setHasError(false);
    return onSignIn(tokenId);
  }

  function handleOnError() {
    setHasError(true);
  }

  const {signIn} = useGoogleLogin({
    clientId,
    accessType: 'offline',
    onSuccess: handleOnSuccess,
    onFailure: handleOnError,
  });

  return {googleSignIn: signIn, error: hasError};
}

Sign-out hook

import {useGoogleLogout} from 'react-google-login';

const clientId = process.env.REACT_APP_GOOGLE_CLIENT_ID as string;

type CallbackFunction = () => void;

export function useGoogleSignOut(
  onSignOut: CallbackFunction
): CallbackFunction {
  function handleOnSuccess() {
    return onSignOut();
  }

  function handleOnError() {
    // Let's keep with the sign out process.
    return onSignOut();
  }

  const {signOut} = useGoogleLogout({
    clientId,
    accessType: 'offline',
    onLogoutSuccess: handleOnSuccess,
    onFailure: handleOnError,
  });

  return signOut;
}

Use in your page

Pass your login callback that will forward the google token to your backend.

function LoginPage() {
  const {signIn} = useAuth();
  const {googleSignIn, error} = useGoogleSignIn(signIn);

  return <div>...</div>;
}