@magicbell/react-headless
Version:
Hooks to build a notification inbox
47 lines • 2.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useNotifications;
const tslib_1 = require("tslib");
const react_1 = require("react");
const index_js_1 = tslib_1.__importDefault(require("../stores/config/index.js"));
const index_js_2 = require("../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');
*/
function useNotifications(storeId = 'default') {
const { stores, fetchStore, markAllAsSeen, markAllAsRead } = (0, index_js_2.useNotificationStoresCollection)();
const config = (0, index_js_1.default)();
const store = stores[storeId];
const fetch = (0, react_1.useCallback)((queryParams, options) => fetchStore(storeId, queryParams, options), [fetchStore, storeId]);
const fetchNextPage = (0, react_1.useCallback)((queryParams = {}, options) => {
const page = store.currentPage + 1;
return fetchStore(storeId, { ...queryParams, page }, options);
}, [fetchStore, storeId, store?.currentPage]);
(0, react_1.useEffect)(() => {
if (!store)
return;
if (!config.lastFetchedAt || store.lastFetchedAt)
return;
void fetch({ page: 1 });
}, [config.lastFetchedAt, store, fetch]);
const markAllAsReadFn = (0, react_1.useCallback)((options) => markAllAsRead({ ...options, storeId }), [markAllAsRead, storeId]);
const markAllAsSeenFn = (0, react_1.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