Refactor useNotificationsStream hook to improve parameter handling and conditional subscription

- Updated the `useNotificationsStream` hook to destructure parameters directly in the function signature for clarity.
- Added a conditional check to prevent subscription when the `enabled` flag is false, enhancing performance and preventing unnecessary operations.
- Adjusted dependencies in the `useEffect` hook to ensure proper reactivity based on the new parameter structure.
This commit is contained in:
gbuomprisco
2025-09-17 13:08:34 +08:00
parent 530e127000
commit c719884cbd

View File

@@ -11,7 +11,11 @@ type Notification = {
link: string | null; link: string | null;
}; };
export function useNotificationsStream(params: { export function useNotificationsStream({
onNotifications,
accountIds,
enabled,
}: {
onNotifications: (notifications: Notification[]) => void; onNotifications: (notifications: Notification[]) => void;
accountIds: string[]; accountIds: string[];
enabled: boolean; enabled: boolean;
@@ -19,6 +23,10 @@ export function useNotificationsStream(params: {
const client = useSupabase(); const client = useSupabase();
useEffect(() => { useEffect(() => {
if (!enabled) {
return;
}
const channel = client.channel('notifications-channel'); const channel = client.channel('notifications-channel');
const subscription = channel const subscription = channel
@@ -27,12 +35,11 @@ export function useNotificationsStream(params: {
{ {
event: 'INSERT', event: 'INSERT',
schema: 'public', schema: 'public',
filter: `account_id=in.(${params.accountIds.join(', ')})`, filter: `account_id=in.(${accountIds.join(', ')})`,
table: 'notifications', table: 'notifications',
}, },
(payload) => { (payload) => {
console.log('payload', payload); onNotifications([payload.new as Notification]);
params.onNotifications([payload.new as Notification]);
}, },
) )
.subscribe(); .subscribe();
@@ -40,5 +47,5 @@ export function useNotificationsStream(params: {
return () => { return () => {
void subscription?.unsubscribe(); void subscription?.unsubscribe();
}; };
}, [client, params]); }, [client, onNotifications, accountIds, enabled]);
} }