Skip to content

Commit

Permalink
feat: create useDeepCompareCallback
Browse files Browse the repository at this point in the history
  • Loading branch information
pedromtec committed Jan 13, 2025
1 parent 63d9790 commit dd50dd1
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions packages/core/src/components/cart/CartSidebar/CartSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,14 @@ import type {

import type { CurrencyCode, ViewCartEvent } from '@faststore/sdk'
import { Icon, useFadeEffect, useUI } from '@faststore/ui'
import { ReactNode, useCallback, useEffect, useMemo } from 'react'
import {
DependencyList,
ReactNode,
useCallback,
useEffect,
useMemo,
useRef,
} from 'react'
import { useCart } from 'src/sdk/cart'
import { useCheckoutButton } from 'src/sdk/cart/useCheckoutButton'
import { useSession } from 'src/sdk/session'
Expand Down Expand Up @@ -61,13 +68,31 @@ const OrderSummary = dynamic(

import styles from './section.module.scss'

function useDeepCompareCallback<T extends Function>(
callback: T,
dependencies: DependencyList
): T {
const previousDeps = useRef<DependencyList>()

const isEqual = (a: unknown, b: unknown) =>
JSON.stringify(a) === JSON.stringify(b)

if (!isEqual(previousDeps.current, dependencies)) {
previousDeps.current = dependencies
}

// eslint-disable-next-line react-hooks/exhaustive-deps
return useCallback(callback, previousDeps.current)
}

function useViewCartEvent() {
const {
currency: { code },
} = useSession()
const { items, gifts, total } = useCart()

const sendViewCartEvent = useCallback(() => {
const sendViewCartEvent = useDeepCompareCallback(() => {
console.log({ code, gifts, items, total })
import('@faststore/sdk').then(({ sendAnalyticsEvent }) => {
return sendAnalyticsEvent<ViewCartEvent>({
name: 'view_cart',
Expand Down Expand Up @@ -155,7 +180,7 @@ function CartSidebar({
if (!displayCart) {
return
}

console.log({ displayCart })
sendViewCartEvent()
}, [displayCart, sendViewCartEvent])

Expand Down

0 comments on commit dd50dd1

Please sign in to comment.