Skip to content

Instantly share code, notes, and snippets.

@generalsystems
Last active September 30, 2021 19:15
Show Gist options
  • Select an option

  • Save generalsystems/2fda5f061ba44d821b89032c2d499199 to your computer and use it in GitHub Desktop.

Select an option

Save generalsystems/2fda5f061ba44d821b89032c2d499199 to your computer and use it in GitHub Desktop.
Pull data from google analytics
// Add this script tag the index.html file
<script src="https://apis.google.com/js/client:platform.js"></script>
// Initialize the library with your credentials
const initialize = () => {
return window.gapi.auth2.init({
client_id: "YOUR_CLIENT_ID", //paste your client ID here
scope: "https://www.googleapis.com/auth/analytics.readonly",
});
};
// To get the client ID
/*
1) go Here https://console.developers.google.com/flows/enableapi?apiid=analyticsreporting.googleapis.com&credential=client_key
2) select a google cloud project or create a new one
3) Enable the aAnalytics Reporting Api
4) Go to credentials --> Select Analytics Reporting API & Web browser (javascript) & select user data
5) complete application infos
6) create credentials --> web application --> set your authorized origins e.g http://localhost:3000
7) copy client ID
*/
export const checkSignedIn = () => {
return new Promise((resolve, reject) => {
initialize() //calls the previous function
.then(() => {
const auth = window.gapi.auth2.getAuthInstance(); //returns the GoogleAuth object
resolve(auth.isSignedIn.get()); //returns whether the current user is currently signed in
})
.catch((error) => {
reject(error);
});
});
};
export const renderSignInButton = () => {
window.gapi.signin2.render("signin-button", {
scope: "profile email",
width: 210,
height: 70,
longtitle: true,
// theme: "dark",
onsuccess: (googleUser) => {
console.log("Logged in as: " + googleUser.getBasicProfile().getName());
},
onfailure: (error) => {
console.error(error);
}
});
};
// Initialize in root component
function Container() {
const [isSignedIn, setIsSignedIn] = useState(false);
const updateSignin = (signedIn) => {
setIsSignedIn(signedIn);
if (!signedIn) {
renderSignInButton();
}
};
const init = () => {
checkSignedIn()
.then((signedIn) => {
updateSignin(signedIn);
})
.catch((error) => {
console.error(error);
});
};
useEffect(() => {
window.gapi.load("auth2", init)
});
return (
<div>
{!isSignedIn ? (
<div id="signin-button"></div>
) : (
<View />
)}
</div>
);
}
const View = () => {
const [data, setData] = useState([]);
useEffect(() => {
const queryReport = () => {//(1)
window.gapi.client
.request({
path: "/v4/reports:batchGet",
root: "https://analyticsreporting.googleapis.com/",
method: "POST",
body: {
reportRequests: [
{
viewId: "YOUR_VIEW_ID", //enter your view ID here
// To get Your client ID go to your google analytics dashboard ---> Admin ---> View settings
dateRanges: [
{
startDate: "10daysAgo",
endDate: "today",
},
],
metrics: [
{
// Change metric this to what you want checkout this resource https://ga-dev-tools.web.app/dimensions-metrics-explorer/
// change the displayResults function accordingly
expression: "ga:users",
},
],
dimensions: [
{
// Change the corresponding Dimensions to the metrics above
// change the displayResults function accordingly
name: "ga:date",
},
],
},
],
},
})
.then(displayResults);
};
const displayResults = (response) => {//(2)
const queryResult = response.result.reports[0].data.rows;
const result = queryResult.map((row) => {
const dateSting = row.dimensions[0];
const formattedDate = `${dateSting.substring(0, 4)}
-${dateSting.substring(4, 6)}-${dateSting.substring(6, 8)}`;
return {
date: formattedDate,
visits: row.metrics[0].values[0],
};
});
setData(result);
};
queryReport();
}, []);
return (
<>
{
data.map((row) => (
<div key={row.date}>{`${row.date}: ${row.visits} visits`}</div>
))
}
</>
)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment