Skip to content

Commit

Permalink
remove duplicates when adding announcements to array
Browse files Browse the repository at this point in the history
  • Loading branch information
beebls committed Sep 14, 2024
1 parent 5b9613c commit 91e4d6c
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions frontend/src/components/AnnouncementsDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,30 @@ 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(() => {
void fetchAnnouncement();
}, []);
useEffect(() => {
if (hiddenAnnouncementIds.length > 0) {
setAnnouncements((oldAnnouncement) => [welcomeAnnouncement, ...oldAnnouncement]);
addAnnouncements([welcomeAnnouncement]);
}
}, [hiddenAnnouncementIds]);

Expand Down

0 comments on commit 91e4d6c

Please sign in to comment.