From b55b02e2f97e58fa111deb9b826a58f0b8c4ab75 Mon Sep 17 00:00:00 2001 From: Giancarlo Buomprisco Date: Wed, 14 May 2025 21:27:35 +0700 Subject: [PATCH] Refactor auth event handling with improved typing and callbacks (#254) Simplify and enhance the `onEvent` logic by using `useCallback` for better performance and typing with `AuthChangeEvent` and `Session`. Add handling for the `INITIAL_SESSION` event, ensuring proper user identification and monitoring initialization. --- apps/web/components/auth-provider.tsx | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/apps/web/components/auth-provider.tsx b/apps/web/components/auth-provider.tsx index 236e8104f..9efc5331a 100644 --- a/apps/web/components/auth-provider.tsx +++ b/apps/web/components/auth-provider.tsx @@ -2,6 +2,8 @@ import { useCallback } from 'react'; +import type { AuthChangeEvent, Session } from '@supabase/supabase-js'; + import { useMonitoring } from '@kit/monitoring/hooks'; import { useAppEvents } from '@kit/shared/events'; import { useAuthChangeListener } from '@kit/supabase/hooks/use-auth-change-listener'; @@ -11,13 +13,18 @@ import pathsConfig from '~/config/paths.config'; export function AuthProvider(props: React.PropsWithChildren) { const dispatchEvent = useDispatchAppEventFromAuthEvent(); - useAuthChangeListener({ - appHomePath: pathsConfig.app.home, - onEvent: (event, session) => { + const onEvent = useCallback( + (event: AuthChangeEvent, session: Session | null) => { dispatchEvent(event, session?.user.id, { email: session?.user.email ?? '', }); }, + [dispatchEvent], + ); + + useAuthChangeListener({ + appHomePath: pathsConfig.app.home, + onEvent, }); return props.children; @@ -29,11 +36,23 @@ function useDispatchAppEventFromAuthEvent() { return useCallback( ( - type: string, + type: AuthChangeEvent, userId: string | undefined, traits: Record = {}, ) => { switch (type) { + case 'INITIAL_SESSION': + if (userId) { + emit({ + type: 'user.signedIn', + payload: { userId, ...traits }, + }); + + monitoring.identifyUser({ id: userId, ...traits }); + } + + break; + case 'SIGNED_IN': if (userId) { emit({