diff --git a/hooks/use-unread-announcements.ts b/hooks/use-unread-announcements.ts index f1a9979c..2655cf7a 100644 --- a/hooks/use-unread-announcements.ts +++ b/hooks/use-unread-announcements.ts @@ -40,17 +40,24 @@ export function useUnreadAnnouncements() { // Mark an announcement as read const markAsRead = (announcementId: string) => { - setReadAnnouncements((prev: AnnouncementRead) => ({ - ...prev, - [announcementId]: true - })); - - // Check if there are still any unread announcements - const hasUnreadAnnouncements = announcements.some(announcement => { - return !readAnnouncements[announcement.id] && announcement.id !== announcementId; + setReadAnnouncements((prev: AnnouncementRead) => { + const newState = { + ...prev, + [announcementId]: true + }; + + // Check if there are still any unread announcements using the updated state + const hasUnreadAnnouncements = announcements.some(announcement => { + return !newState[announcement.id]; + }); + + // Update the hasUnread state in the next tick to avoid the infinite loop + setTimeout(() => { + setHasUnread(hasUnreadAnnouncements); + }, 0); + + return newState; }); - - setHasUnread(hasUnreadAnnouncements); }; // Mark all announcements as read @@ -61,12 +68,22 @@ export function useUnreadAnnouncements() { }); setReadAnnouncements(allRead); - setHasUnread(false); + + // Update the hasUnread state in the next tick to avoid the infinite loop + setTimeout(() => { + setHasUnread(false); + }, 0); }; // Check for unread announcements on mount useEffect(() => { - checkForUnreadAnnouncements(); + // Run the check in the next tick to avoid unnecessary re-renders + const timer = setTimeout(() => { + checkForUnreadAnnouncements(); + }, 0); + + // Cleanup timer on component unmount + return () => clearTimeout(timer); }, []); return {