How to use gapi in react

I had a lot a problems trying to add the gapi at my react project. All the packages that I found were outdated, so I created a new one.

gapi-script allow you to add gapi with:

import { gapi } from 'gapi-script'

I made a custom Hook for this!

import { useEffect } from 'react';

const useGoogle = () => {

    useEffect(() => {

        const SCOPE = "TODO: your scope here";
        const handleClientLoad = () => window.gapi.load('client:auth2', initClient);
    
        const initClient = () => {
            const discoveryUrl = "TODO: your discoveryUrl here";
            window.gapi.client.init({
                'clientId': "TODO: your client id here",
                'discoveryDocs': [discoveryUrl],
                'scope': SCOPE
            });
            console.log("Google loaded");
        };

        const script = document.createElement('script');

        script.src = "https://apis.google.com/js/api.js";
        script.async = true;
        script.defer = true;
        script.onload = handleClientLoad;

        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };

    }, []);
};

export default useGoogle;

Assuming you are using create-react-app and you have webpack configured with a public HTML folder, than that is where you will need to place your script tag.

You may not see your public folder in certain text editor project trees, but you will see it in your OS file browser. Simply go to the public folder and edit index.html with the line:

<script src="https://apis.google.com/js/client.js"></script>

right above the closing </head> tag. You are doing this indirectly with your current code anyway. You can remove:

 const script = document.createElement("script");
 script.src = "https://apis.google.com/js/client.js";

and the onload call, placing all of your api object calls (with window as the base object) in your componentDidMount() method. You don't have to worry about it being loaded as your component can only mount after everything is loaded.

Also, don't worry about it slowing anything down or loading the script before you need it. When you run npm run build before production you will condense everything into a few files anyway.

EDIT:

You should change your onload call to addEventListener('load', callback);