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.
This commit is contained in:
Giancarlo Buomprisco
2025-05-14 21:27:35 +07:00
committed by GitHub
parent dd3d5ddf96
commit b55b02e2f9

View File

@@ -2,6 +2,8 @@
import { useCallback } from 'react'; import { useCallback } from 'react';
import type { AuthChangeEvent, Session } from '@supabase/supabase-js';
import { useMonitoring } from '@kit/monitoring/hooks'; import { useMonitoring } from '@kit/monitoring/hooks';
import { useAppEvents } from '@kit/shared/events'; import { useAppEvents } from '@kit/shared/events';
import { useAuthChangeListener } from '@kit/supabase/hooks/use-auth-change-listener'; 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) { export function AuthProvider(props: React.PropsWithChildren) {
const dispatchEvent = useDispatchAppEventFromAuthEvent(); const dispatchEvent = useDispatchAppEventFromAuthEvent();
useAuthChangeListener({ const onEvent = useCallback(
appHomePath: pathsConfig.app.home, (event: AuthChangeEvent, session: Session | null) => {
onEvent: (event, session) => {
dispatchEvent(event, session?.user.id, { dispatchEvent(event, session?.user.id, {
email: session?.user.email ?? '', email: session?.user.email ?? '',
}); });
}, },
[dispatchEvent],
);
useAuthChangeListener({
appHomePath: pathsConfig.app.home,
onEvent,
}); });
return props.children; return props.children;
@@ -29,11 +36,23 @@ function useDispatchAppEventFromAuthEvent() {
return useCallback( return useCallback(
( (
type: string, type: AuthChangeEvent,
userId: string | undefined, userId: string | undefined,
traits: Record<string, string> = {}, traits: Record<string, string> = {},
) => { ) => {
switch (type) { switch (type) {
case 'INITIAL_SESSION':
if (userId) {
emit({
type: 'user.signedIn',
payload: { userId, ...traits },
});
monitoring.identifyUser({ id: userId, ...traits });
}
break;
case 'SIGNED_IN': case 'SIGNED_IN':
if (userId) { if (userId) {
emit({ emit({