UNPKG

@magicbell/react-headless

Version:

Hooks to build a notification inbox

43 lines 1.85 kB
import { useCallback, useEffect } from 'react'; import useConfig from '../stores/config/index.js'; import { useNotificationStoresCollection } from '../stores/notifications/index.js'; /** * Hook to get a notifications store from the stores collection. It fetches the * first page of the store if it is not fetched already. * * @param storeId ID of the notifications store (optional) * * @example * const store = useNotifications('mentions'); */ export default function useNotifications(storeId = 'default') { const { stores, fetchStore, markAllAsSeen, markAllAsRead } = useNotificationStoresCollection(); const config = useConfig(); const store = stores[storeId]; const fetch = useCallback((queryParams, options) => fetchStore(storeId, queryParams, options), [fetchStore, storeId]); const fetchNextPage = useCallback((queryParams = {}, options) => { const page = store.currentPage + 1; return fetchStore(storeId, { ...queryParams, page }, options); }, [fetchStore, storeId, store?.currentPage]); useEffect(() => { if (!store) return; if (!config.lastFetchedAt || store.lastFetchedAt) return; void fetch({ page: 1 }); }, [config.lastFetchedAt, store, fetch]); const markAllAsReadFn = useCallback((options) => markAllAsRead({ ...options, storeId }), [markAllAsRead, storeId]); const markAllAsSeenFn = useCallback((options) => markAllAsSeen({ ...options, storeId }), [markAllAsSeen, storeId]); if (!store) return null; return { ...store, isEmpty: store.notifications.length === 0, hasNextPage: store.currentPage < store.totalPages, fetch, fetchNextPage, markAllAsSeen: markAllAsSeenFn, markAllAsRead: markAllAsReadFn, }; } //# sourceMappingURL=useNotifications.js.map