[英]How to make a google analytics reporting API request from a react component?
I am trying to build an analytics dashboard with React/Gatsby and the Google Analytics Reporting API v4.我正在尝试使用 React/Gatsby 和 Google Analytics Reporting API v4 构建分析仪表板。 I have included the scripts in my layout component from the google api quickstart guide .
我已将来自google api 快速入门指南的脚本包含在我的布局组件中。
I know it's loading on the page, because in the browser developer tools console I can access window.gapi
and the google sign in button appears correctly.我知道它正在页面上加载,因为在浏览器开发人员工具控制台中我可以访问
window.gapi
并且谷歌登录按钮正确显示。 But in my page component, I have a useEffect hook.但是在我的页面组件中,我有一个 useEffect 挂钩。 When the component mounts, I want to make a request using
window.gapi.client.request(...)
.当组件安装时,我想使用
window.gapi.client.request(...)
发出请求。
I tried wrapping the request in this: if (typeof window.== undefined) {... }
as per the gatsby docs我尝试在此包装请求:
if (typeof window.== undefined) {... }
根据gatsby 文档
Layout.js布局.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索引.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'))
}
}
I expect to have access to window.gapi from the useEffect hook, but I get TypeError: window.gapi is undefined
.我希望可以从 useEffect 挂钩访问 window.gapi ,但我得到
TypeError: window.gapi is undefined
。
You can try using the setInterval
function to see when window.gapi
is loaded, then clear it after it loads:您可以尝试使用
setInterval
function 查看window.gapi
加载,然后在加载后将其清除:
useEffect(window.interval = setInterval(waitForAPI, 1000), [])
waitForAPI() {
if (window.gapi.client.request !== undefined) {
querySuccessfulSubmissions();
clearInterval( window.interval );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.