From 14d4585d29d25cd75ee3095cc7f0c74f86f9eff8 Mon Sep 17 00:00:00 2001 From: mizdra Date: Sat, 11 May 2024 19:41:53 +0900 Subject: [PATCH] Fix the error when touching the screen before `` is mounted (#152) * refactor: `scrollable` may be undefined * fix: ignore onTouchMove event if scrollable is undefined * chore: add example to reproduce #151 * Revert "chore: add example to reproduce #151" This reverts commit ac7ec0e97f6c751102315815bc814f771e0202a2. --- src/use-prevent-scroll.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/use-prevent-scroll.ts b/src/use-prevent-scroll.ts index 80e112c..40ea1b1 100644 --- a/src/use-prevent-scroll.ts +++ b/src/use-prevent-scroll.ts @@ -102,7 +102,7 @@ function preventScrollStandard() { // 6. As a last resort, handle window scroll events, and scroll back to the top. This can happen when attempting // to navigate to an input with the next/previous buttons that's outside a modal. function preventScrollMobileSafari() { - let scrollable: Element; + let scrollable: Element | undefined; let lastY = 0; let onTouchStart = (e: TouchEvent) => { // Store the nearest scrollable parent element from the element that the user touched. @@ -118,6 +118,13 @@ function preventScrollMobileSafari() { }; let onTouchMove = (e: TouchEvent) => { + // In special situations, `onTouchStart` may be called without `onTouchStart` being called. + // (e.g. when the user places a finger on the screen before the is mounted and then moves the finger after it is mounted). + // If `onTouchStart` is not called, `scrollable` is `undefined`. Therefore, such cases are ignored. + if (scrollable === undefined) { + return; + } + // Prevent scrolling the window. if ( scrollable === document.documentElement ||