'How to use gapi in react
I want to use gapi to access people api resources from google, I tried many ways to do the job, but I still cannot get any response. It has not error, no warning. Here is my code.
loadYoutubeApi() {
const script = document.createElement("script");
script.src = "https://apis.google.com/js/client.js";
script.onload = () => {
window.gapi.load('client', () => {
window.gapi.client.setApiKey(types.API_KEY)
window.gapi.client.setClientId(types.CLIENT_ID)
window.gapi.client.setDiscoveryDocs(types.DISCOVERY_DOCS)
window.gapi.client.setScope(types.SCOPE)
window.gapi.client.load('client:auth2', 'v3', () => {
console.log("gapi is ready")
this.setState({ gapiReady: true });
});
});
};
document.body.appendChild(script);
}
componentDidMount() {
this.loadYoutubeApi();
}
Can anyone tell me why I cant even get the console log info, is it actually working?
Update:
Once I commented these codes out
window.gapi.client.setClientId(types.CLIENT_ID)
window.gapi.client.setDiscoveryDocs(types.DISCOVERY_DOCS)
window.gapi.client.setScope
I can get my console info, is it something to do with those methods?
Update:
I can get gapi object and console.log(window.gapi) to see its detail.
Solution 1:[1]
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'
Solution 2:[2]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucas Andrade |
| Solution 2 | Alexis Poveda |
