From 7ef016f3f007743ce91ae69082c2e50d870a6aec Mon Sep 17 00:00:00 2001 From: Andrew Prifer <2991360+AndrewPrifer@users.noreply.github.com> Date: Tue, 22 Nov 2022 14:24:23 +0100 Subject: [PATCH] Make notifications SSR ready (#341) Properly check if window exists --- theatre/shared/src/notify.ts | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/theatre/shared/src/notify.ts b/theatre/shared/src/notify.ts index 6b365e7..285329f 100644 --- a/theatre/shared/src/notify.ts +++ b/theatre/shared/src/notify.ts @@ -64,8 +64,10 @@ const createHandler = } } - // @ts-ignore - return window?.[globalVariableNames.notifications]?.notify[type](...args) + return typeof window !== 'undefined' + ? // @ts-ignore + window[globalVariableNames.notifications]?.notify[type](...args) + : undefined } export const notify: Notifiers = { @@ -75,16 +77,18 @@ export const notify: Notifiers = { error: createHandler('error'), } -window?.addEventListener('error', (e) => { - notify.error( - `An error occurred`, - `
${e.message}\n\nSee **console** for details.`, - ) -}) +if (typeof window !== 'undefined') { + window.addEventListener('error', (e) => { + notify.error( + `An error occurred`, + `
${e.message}\n\nSee **console** for details.`, + ) + }) -window?.addEventListener('unhandledrejection', (e) => { - notify.error( - `An error occurred`, - `
${e.reason}\n\nSee **console** for details.`, - ) -}) + window.addEventListener('unhandledrejection', (e) => { + notify.error( + `An error occurred`, + `
${e.reason}\n\nSee **console** for details.`, + ) + }) +}