How to use gapi in react

我是研究僧i 提交于 2020-05-29 04:51:31

问题


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.


回答1:


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);




回答2:


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'


来源:https://stackoverflow.com/questions/51977448/how-to-use-gapi-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!