Skip to content

Commit

Permalink
Added Shopify Analitics Package to test it
Browse files Browse the repository at this point in the history
  • Loading branch information
CodastickFantastic committed Apr 8, 2024
1 parent 970c702 commit 7993c9b
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 4 deletions.
7 changes: 7 additions & 0 deletions app/graphql/storefrontClient/Shop.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export const SHOP_DATA = `#graphql
query Shop {
shop{
id
name
}
}`
40 changes: 40 additions & 0 deletions app/lib/shopifyAnalitics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { useMatches } from '@remix-run/react';
import { useMemo } from 'react';

const DEFAULT_LOCALE = {/* Empty for demonstration purposes.*/ }

/**
* Custom hook to aggregate `analytics` data returned by Remix loaders
* @param hasUserConsent {Boolean}
* @returns Object with aggregated analytics data
*/
export function usePageAnalytics({ hasUserConsent }) {
// useMatches returns an array of nested routes
const matches = useMatches();

// useMemo improves performance by only running when `matches` changes.
const analyticsFromMatches = useMemo(() => {
const data = {};

// For each nested route, get the `analytics` object returned
// by its loader function and assign to `data`
matches.forEach((event) => {
const eventData = event?.data;
if (eventData) {
eventData['analytics'] && Object.assign(data, eventData['analytics']);

// This hook also allows you to optionally collect data such as
// currency and language preferences.
const selectedLocale = eventData['selectedLocale'] || DEFAULT_LOCALE;
Object.assign(data, {
currency: selectedLocale.currency,
acceptedLanguage: selectedLocale.language,
});
}
});

return { ...data, hasUserConsent };
}, [matches]);

return analyticsFromMatches;
}
48 changes: 46 additions & 2 deletions app/root.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import {
useLoaderData,
ScrollRestoration,
isRouteErrorResponse,
useLocation
} from '@remix-run/react';
import { useNonce, Script, Seo } from '@shopify/hydrogen';
import {
useNonce, Script, Seo, ShopifySalesChannel, AnalyticsEventName,
getClientBrowserParameters, sendShopifyAnalytics, useShopifyCookies
} from '@shopify/hydrogen';

import seoRoot from './seo/seoRoot';
import { Layout } from '~/components/layout/Layout';
Expand All @@ -23,6 +27,10 @@ import appStyles from './styles/app.css';

import ReactGA from 'react-ga4';

import { SHOP_DATA } from '~/graphql/storefrontClient/Shop';
import { usePageAnalytics } from './lib/shopifyAnalitics';
import { useEffect, useRef } from 'react';

/**
* This is important to avoid re-fetching root queries on sub-navigations
* @type {ShouldRevalidateFunction}
Expand Down Expand Up @@ -94,11 +102,18 @@ export async function loader({ context }) {

const seo = seoRoot;

// Need to add Shopify Analitics
const { shop } = await storefront.query(SHOP_DATA);

return defer(
{
cart: cartPromise,
isLoggedIn: isLoggedInPromise,
seo
seo,
analytics: {
shopifySalesChannel: ShopifySalesChannel.hydrogen,
shopId: shop.id,
},
},
{
headers: {
Expand All @@ -116,6 +131,35 @@ export default function App() {

ReactGA.initialize("G-9DDDZQ83F9");

const hasUserConsent = true;
useShopifyCookies({ hasUserConsent })

// The user's current location
const location = useLocation();
// The user's last location. Blank to start.
const lastLocationKey = useRef('');
// Analytics data returned by the custom hook
const pageAnalytics = usePageAnalytics({ hasUserConsent });

useEffect(() => {
// Only continue if the user's location changed.
if (lastLocationKey.current === location.key) return;
lastLocationKey.current = location.key;

// Analytics data, including browser information
const payload = {
...getClientBrowserParameters(),
...pageAnalytics,
};

// Send analytics payload to Shopify
sendShopifyAnalytics({
eventName: AnalyticsEventName.PAGE_VIEW,
payload,
});

}, [location]);

return (
<html lang="pl-PL">
<head>
Expand Down
8 changes: 6 additions & 2 deletions app/routes/produkty.$handle.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useLoaderData, useLocation, Link, useSearchParams, useNavigation } from "@remix-run/react"
import { Image, Money } from "@shopify/hydrogen-react"
import { CartForm } from "@shopify/hydrogen"
import { CartForm, AnaliticsPageType } from "@shopify/hydrogen"
import { json } from "@shopify/remix-oxygen"
import { useState, useRef, useEffect } from "react"
import emailjs from '@emailjs/browser';
Expand Down Expand Up @@ -40,7 +40,11 @@ export async function loader({ params, context, request }) {
product,
selectedVariant,
shop,
seo
seo,
analytics: {
pageType: AnalyticsPageType.product,
products: [product],
}
})
}

Expand Down

0 comments on commit 7993c9b

Please sign in to comment.