UNPKG

@magicbell/magicbell-react

Version:

React components for building a notification inbox for your app

48 lines 2.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = PushNotificationsSubscriber; const react_headless_1 = require("@magicbell/react-headless"); const webpush_1 = require("@magicbell/webpush"); const react_1 = require("react"); /** * Headless component to create subscriptions to push notifications for the * current user. * * @example * <PushNotificationsSubscriber> * {({ createSubscription }) => ( * <button onClick={createSubscription}>Subscribe</button> * )} * <PushNotificationsSubscriber> */ function PushNotificationsSubscriber({ children, serviceWorkerPath = '/service-worker.js', skipServiceWorkerRegistration = false, }) { const isPushAPISupported = (0, webpush_1.isSupported)(); (0, react_1.useEffect)(() => { if (skipServiceWorkerRegistration) return; (0, webpush_1.registerServiceWorker)(serviceWorkerPath).catch((error) => { console.error(`Error registering service worker: ${error}`); }); }, [serviceWorkerPath, skipServiceWorkerRegistration]); const createSubscription = async () => { const credentials = react_headless_1.clientSettings.getState(); if (!credentials?.apiKey) { throw new Error('MagicBell Context was not found, did you wrap this in a MagicBellProvider?'); } if (!credentials.userExternalId && !credentials.userEmail) { throw new Error("Can't subscribe without either a userExternalId or userEmail"); } const options = { host: credentials.serverURL, apiKey: credentials.apiKey, userHmac: credentials.userKey, userExternalId: credentials.userExternalId, userEmail: credentials.userEmail, serviceWorkerPath, }; const client = new webpush_1.WebPushClient(options); return client.subscribe(); }; return children({ createSubscription, isPushAPISupported }); } //# sourceMappingURL=PushNotificationsSubscriber.js.map