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:
committed by
GitHub
parent
dd3d5ddf96
commit
b55b02e2f9
@@ -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<string, string> = {},
|
||||
) => {
|
||||
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({
|
||||
|
||||
Reference in New Issue
Block a user