I am trying to build an analytics dashboard with React/Gatsby and the Google Analytics Reporting API v4. I have included the scripts in my layout component from the google api quickstart guide.
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. But in my page component, I have a useEffect hook. When the component mounts, I want to make a request using window.gapi.client.request(...).
I tried wrapping the request in this: if (typeof window !== undefined) { ... } as per the gatsby docs
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'))
}
}
I expect to have access to window.gapi from the useEffect hook, but I get TypeError: window.gapi is undefined.