Files
myeasycms-v2/packages/features/notifications/src/hooks/use-notifications-stream.ts
giancarlo 9baee90eec Update configuration settings and improve notifications
This commit updates the configuration settings and improves the notification functionality by filtering out duplicate notifications. It also includes changes to feature flag data types and removed dependencies in `package.json`, alongside updates to `pnpm-lock.yaml`.
2024-05-01 12:13:19 +07:00

52 lines
1.2 KiB
TypeScript

import { useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useSupabase } from '@kit/supabase/hooks/use-supabase';
type Notification = {
id: number;
body: string;
dismissed: boolean;
type: 'info' | 'warning' | 'error';
created_at: string;
link: string | null;
};
export function useNotificationsStream(params: {
onNotifications: (notifications: Notification[]) => void;
accountIds: string[];
enabled: boolean;
}) {
const client = useSupabase();
const { data: subscription } = useQuery({
enabled: params.enabled,
queryKey: ['realtime-notifications', ...params.accountIds],
queryFn: () => {
const channel = client.channel('notifications-channel');
return channel
.on(
'postgres_changes',
{
event: 'INSERT',
schema: 'public',
filter: `account_id=in.(${params.accountIds.join(', ')})`,
table: 'notifications',
},
(payload) => {
params.onNotifications([payload.new as Notification]);
},
)
.subscribe();
},
});
useEffect(() => {
return () => {
void subscription?.unsubscribe();
};
}, [subscription]);
}