From 1076067f6a18c93ba7bd8c4dc602280881b620c7 Mon Sep 17 00:00:00 2001 From: Innei Date: Fri, 28 Jul 2023 12:54:35 +0800 Subject: [PATCH] fix: cleanup listener --- src/app/preview/page.tsx | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/app/preview/page.tsx b/src/app/preview/page.tsx index 390398e3ae..6155f06e79 100644 --- a/src/app/preview/page.tsx +++ b/src/app/preview/page.tsx @@ -60,20 +60,21 @@ export default function PreviewPage() { targinOrigin = decodeURIComponent(targinOrigin) window.opener.postMessage('Preview Page Ready', targinOrigin) - window.addEventListener( - 'message', - debounce((e) => { - if (e.origin !== targinOrigin) { - return - } - - const parsedData = JSON.parse(e.data) - - if (parsedData.type === 'preview') { - jotaiStore.set(previewDataAtom, simpleCamelcaseKeys(parsedData.data)) - } - }, 100), - ) + const handler = debounce((e) => { + if (e.origin !== targinOrigin) { + return + } + + const parsedData = JSON.parse(e.data) + + if (parsedData.type === 'preview') { + jotaiStore.set(previewDataAtom, simpleCamelcaseKeys(parsedData.data)) + } + }, 100) + window.addEventListener('message', handler) + return () => { + window.removeEventListener('message', handler) + } }, []) const previewData = useAtomValue(previewDataAtom)