如何从React组件发出Google Analytics Reporting API请求?

我正在尝试使用React / Gatsby和Google Analytics Reporting API v4构建一个分析仪表板。我已经从google api quickstart guide的布局组件中添加了脚本。

我知道它正在页面上加载,因为在浏览器开发人员工具控制台中,我可以访问window.gapi,并且google登录按钮正确显示。但是在页面组件中,我有一个useEffect挂钩。装入组件后,我想使用window.gapi.client.request(...)发出请求。

我尝试根据gatsby docs

将请求包装在if (typeof window !== undefined) { ... }

Layout.js

      <Helmet>
        <meta
          name="google-signin-client_id"
          content="MYCLIENTID"
        />
        <meta
          name="google-signin-scope"
          content="https://www.googleapis.com/auth/analytics.readonly"
        />
        <script src="https://apis.google.com/js/client:platform.js"></script>
      </Helmet>

Index.js

  useEffect(querySuccessfulSubmissions,[])

  function querySuccessfulSubmissions() {
    if (typeof window !== `undefined`) {
      window.gapi.client
        .request({
          path: "/v4/reports:batchGet",root: "https://analyticsreporting.googleapis.com/",method: "POST",body: {
            reportRequests: [
              {
                viewId: "MYVIEWID",samplingLevel: "LARGE",dateRanges: [
                  {
                    startDate: "365daysAgo",endDate: "yesterday",},],metrics: [
                  {
                    expression: `ga:goal1Completions`,alias: "",dimensions: [
                  {
                    name: "ga:yearMonth",})
        .then(response => console.log('success'))
    }
  }

我希望可以从useEffect挂钩访问window.gapi,但我得到TypeError: window.gapi is undefined

minm_in520 回答:如何从React组件发出Google Analytics Reporting API请求?

您可以尝试使用setInterval函数来查看何时加载window.gapi,然后在加载后将其清除:

useEffect(window.interval = setInterval(waitForAPI,1000),[])

waitForAPI() {
    if (window.gapi.client.request !== undefined) {
        querySuccessfulSubmissions();
        clearInterval( window.interval );
    }
}
本文链接:https://www.f2er.com/3141731.html

大家都在问