manifold/web/lib/firebase/notifications.ts
Ian Philips cfbb78af48
Use react-query to cache notifications (#625)
* Use react-query to cache notifications

* Fix imports

* Cleanup

* Limit unseen notifs query

* Catch the bounced query

* Don't use interval

* Unused var

* Avoid flash of page nav

* Give notification question priority & 2 lines

* Right justify timestamps

* Rewording

* Margin

* Simplify error msg

* Be explicit about limit for unseen notifs

* Pass limit > 0
2022-07-07 14:41:50 -06:00

40 lines
1.2 KiB
TypeScript

import { collection, limit, orderBy, query, where } from 'firebase/firestore'
import { Notification } from 'common/notification'
import { db } from 'web/lib/firebase/init'
import { listenForValues } from 'web/lib/firebase/utils'
import { NOTIFICATIONS_PER_PAGE } from 'web/pages/notifications'
export function getNotificationsQuery(
userId: string,
unseenOnlyOptions?: { unseenOnly: boolean; limit: number }
) {
const notifsCollection = collection(db, `/users/${userId}/notifications`)
if (unseenOnlyOptions?.unseenOnly)
return query(
notifsCollection,
where('isSeen', '==', false),
orderBy('createdTime', 'desc'),
limit(unseenOnlyOptions.limit)
)
return query(
notifsCollection,
orderBy('createdTime', 'desc'),
// Nobody's going through 10 pages of notifications, right?
limit(NOTIFICATIONS_PER_PAGE * 10)
)
}
export function listenForNotifications(
userId: string,
setNotifications: (notifs: Notification[]) => void,
unseenOnlyOptions?: { unseenOnly: boolean; limit: number }
) {
return listenForValues<Notification>(
getNotificationsQuery(userId, unseenOnlyOptions),
(notifs) => {
notifs.sort((n1, n2) => n2.createdTime - n1.createdTime)
setNotifications(notifs)
}
)
}