GoogleAuth hooks

Sign-in & sign-out react hooks for google-auth

Thin wrapper over anthonyjgrove/react-google-login

Sign-in hook

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;

export const useGoogleSignIn = (
  onSignIn: CallbackFunction
): {googleSignIn: CallbackFunction; error: boolean} => {
  const [hasError, setHasError] = useState(false);

  const handleOnSuccess = ({tokenId}: GoogleLoginResponse) => {
    setHasError(false);
    return onSignIn(tokenId);
  };

  const 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 const useGoogleSignOut = (onSignOut: CallbackFunction): CallbackFunction => {
  const handleOnSuccess = () => {
    return onSignOut();
  };

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

const LoginPage: FC = () => {
  const {signIn} = useAuth();

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

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