Last active
April 23, 2021 16:56
-
-
Save statico/c6079ed28e032717a0c9bde85518dee8 to your computer and use it in GitHub Desktop.
useOneSignal hook for OneSignal and Next.js with SSR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import getConfig from "next/config" | |
// Add publicRuntimeConfig: { oneSignalAppId: ... } to next.config.js | |
const { publicRuntimeConfig } = getConfig() | |
export const useOneSignal = (externalUserId?: string): void => { | |
// react-onsignal tries to use a global `document` variable, so we can only | |
// use it in the client side. Luckily this method doesn't trigger any "wrong | |
// number of hooks" errors either. | |
if (!process.browser) return | |
const module = require("react-onesignal") | |
const OneSignal = module.default | |
const { useOneSignalSetup } = module | |
const oneSignalAppId = publicRuntimeConfig?.oneSignalAppId | |
OneSignal.initialize(oneSignalAppId, { | |
allowLocalhostAsSecureOrigin: process.env.NODE_ENV !== "production", | |
}) | |
useOneSignalSetup(() => { | |
// This check has to be done within the useOneSignalSetup hook's | |
// callback, otherwise you'll get "wrong number of hooks" errors. | |
if (!externalUserId) return | |
OneSignal.setExternalUserId(externalUserId) | |
OneSignal.registerForPushNotifications() | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment