52 lines
1.7 KiB
TypeScript
52 lines
1.7 KiB
TypeScript
import { useSession } from 'next-auth/react';
|
|
import { useCallback, useRef } from 'react';
|
|
|
|
/**
|
|
* Hook to trigger immediate notification refresh
|
|
* Use this when widgets detect new messages/emails
|
|
*/
|
|
export function useTriggerNotification() {
|
|
const { data: session } = useSession();
|
|
const lastTriggerRef = useRef<number>(0);
|
|
const TRIGGER_DEBOUNCE_MS = 2000; // 2 seconds debounce
|
|
|
|
const triggerNotificationRefresh = useCallback(async () => {
|
|
if (!session?.user?.id) return;
|
|
|
|
// Debounce: prevent multiple triggers within 2 seconds
|
|
const now = Date.now();
|
|
if (now - lastTriggerRef.current < TRIGGER_DEBOUNCE_MS) {
|
|
console.log('[useTriggerNotification] Debouncing trigger (too soon)');
|
|
return;
|
|
}
|
|
lastTriggerRef.current = now;
|
|
|
|
try {
|
|
console.log('[useTriggerNotification] Triggering notification refresh');
|
|
|
|
// Dispatch custom event for immediate UI update
|
|
window.dispatchEvent(new CustomEvent('trigger-notification-refresh'));
|
|
|
|
// Force refresh du notification count en invalidant le cache
|
|
const response = await fetch(`/api/notifications/count?_t=${Date.now()}&force=true`, {
|
|
method: 'GET',
|
|
credentials: 'include',
|
|
cache: 'no-store',
|
|
headers: {
|
|
'Cache-Control': 'no-cache',
|
|
}
|
|
});
|
|
|
|
if (response.ok) {
|
|
console.log('[useTriggerNotification] Notification refresh triggered successfully');
|
|
} else {
|
|
console.warn('[useTriggerNotification] Failed to trigger refresh:', response.status);
|
|
}
|
|
} catch (error) {
|
|
console.error('[useTriggerNotification] Error triggering notification refresh:', error);
|
|
}
|
|
}, [session?.user?.id]);
|
|
|
|
return { triggerNotificationRefresh };
|
|
}
|