Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: sync stores to match context on mark-all-as-seen #8

Merged
merged 2 commits into from
Oct 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/rude-cobras-eat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@magicbell/react-headless': patch
---

ensure that stores are updated to include or remove notification after an mark-all-seen action.
Original file line number Diff line number Diff line change
Expand Up @@ -215,15 +215,49 @@ const useNotificationStoresCollection = create<INotificationsStoresCollection>((

set(
produce<INotificationsStoresCollection>((draft) => {
const changedNotifications = new Map();
const now = Date.now() / 1000;

for (const storeId in stores) {
const { notifications } = stores[storeId];
const { context } = stores[storeId];

draft.stores[storeId].unseenCount = 0;

if (options.updateModels !== false) {
notifications.forEach((notification, index) => {
draft.stores[storeId].notifications[index] = mergeRight(notification, { seenAt: Date.now() / 1000 });
});
if (options.updateModels === false) continue;

// don't iterate over notifications in stores that only hold seen notifications
if (context.seen !== true) {
for (const notification of draft.stores[storeId].notifications) {
// don't change notifications that are already seen
if (notification.seenAt) continue;

notification.seenAt = now;
changedNotifications.set(notification.id, notification);
}
}

// stores that don't include seen notifications, can be flushed
if (context.seen === false) {
draft.stores[storeId].notifications = [];
draft.stores[storeId].total = 0;
}
}

// do a second pass to update the notifications in the stores that don't hold seen notifications
for (const storeId in stores) {
const { context } = stores[storeId];
// skip stores that already hold seen notifications
if (context.seen !== true) continue;

const notifications = draft.stores[storeId].notifications;
for (const notification of changedNotifications.values()) {
if (
objMatchesContext(notification, context).result &&
!notifications.find((n) => n.id === notification.id)
) {
notifications.push(notification);
draft.stores[storeId].total += 1;
}
}
}
}),
Expand Down