From 91e4d6ca6dae215bcd258056bc3760507ba9a50a Mon Sep 17 00:00:00 2001
From: Beebles <102569435+beebls@users.noreply.github.com>
Date: Fri, 13 Sep 2024 18:32:22 -0600
Subject: remove duplicates when adding announcements to array

---
 frontend/src/components/AnnouncementsDisplay.tsx | 17 +++++++++++++++--
 1 file changed, 15 insertions(+), 2 deletions(-)

(limited to 'frontend/src/components/AnnouncementsDisplay.tsx')

diff --git a/frontend/src/components/AnnouncementsDisplay.tsx b/frontend/src/components/AnnouncementsDisplay.tsx
index 66154192..04ce2fa1 100644
--- a/frontend/src/components/AnnouncementsDisplay.tsx
+++ b/frontend/src/components/AnnouncementsDisplay.tsx
@@ -33,9 +33,22 @@ export function AnnouncementsDisplay() {
   // showWelcome will display a welcome motd, the welcome motd has an id of "welcome" and once that is saved to hiddenMotdId, it will not show again
   const [hiddenAnnouncementIds, setHiddenAnnouncementIds] = useSetting<string[]>('hiddenAnnouncementIds', []);
 
+  function addAnnouncements(newAnnouncements: Announcement[]) {
+    // Removes any duplicates and sorts by created date
+    setAnnouncements((oldAnnouncements) => {
+      const newArr = [...oldAnnouncements, ...newAnnouncements];
+      const setOfIds = new Set(newArr.map((a) => a.id));
+      return Array.from(setOfIds)
+        .map((id) => newArr.find((a) => a.id === id)!)
+        .sort((a, b) => {
+          return new Date(b.created).getTime() - new Date(a.created).getTime();
+        });
+    });
+  }
+
   async function fetchAnnouncement() {
     const announcements = await getAnnouncements();
-    announcements && setAnnouncements((oldAnnouncements) => [...announcements, ...oldAnnouncements]);
+    announcements && addAnnouncements(announcements);
   }
 
   useEffect(() => {
@@ -43,7 +56,7 @@ export function AnnouncementsDisplay() {
   }, []);
   useEffect(() => {
     if (hiddenAnnouncementIds.length > 0) {
-      setAnnouncements((oldAnnouncement) => [welcomeAnnouncement, ...oldAnnouncement]);
+      addAnnouncements([welcomeAnnouncement]);
     }
   }, [hiddenAnnouncementIds]);
 
-- 
cgit v1.2.3

