From 831ca3a8dbe8f439025b7d3aadb7160b0632d491 Mon Sep 17 00:00:00 2001 From: Daniel Schmidt <3764345+thebuilder@users.noreply.github.com> Date: Thu, 14 Mar 2019 22:38:57 +0100 Subject: [PATCH] refactor: change the Map loop to forEach (#200) * refactor: change the Map loop to forEach Using for...of created a lot of babel bloat, while requiring Symbol.iterator to be defined. * Sync with Prettier --- src/intersection.ts | 5 ++--- src/useInView.tsx | 51 ++++++++++++++++++++++++--------------------- 2 files changed, 29 insertions(+), 27 deletions(-) diff --git a/src/intersection.ts b/src/intersection.ts index 9ef57a0f..5bb610b7 100644 --- a/src/intersection.ts +++ b/src/intersection.ts @@ -112,18 +112,17 @@ export function unobserve(element: Element | null) { let rootObserved = false /* istanbul ignore else */ if (observerId) { - for (let [key, item] of INSTANCE_MAP) { + INSTANCE_MAP.forEach((item, key) => { if (key !== element) { if (item.observerId === observerId) { itemsLeft = true rootObserved = true - break } if (item.observer.root === root) { rootObserved = true } } - } + }) } if (!rootObserved && root) ROOT_IDS.delete(root) if (observer && !itemsLeft) { diff --git a/src/useInView.tsx b/src/useInView.tsx index d39ef820..5c2afffb 100644 --- a/src/useInView.tsx +++ b/src/useInView.tsx @@ -15,32 +15,35 @@ export function useInView(options: IntersectionOptions = {}): HookResponse { entry: undefined, }) - React.useEffect(() => { - if (!ref) return - observe( - ref, - (inView, intersection) => { - setState({ inView, entry: intersection }) + React.useEffect( + () => { + if (!ref) return + observe( + ref, + (inView, intersection) => { + setState({ inView, entry: intersection }) - if (inView && options.triggerOnce) { - // If it should only trigger once, unobserve the element after it's inView - unobserve(ref) - } - }, - options, - ) + if (inView && options.triggerOnce) { + // If it should only trigger once, unobserve the element after it's inView + unobserve(ref) + } + }, + options, + ) - return () => { - unobserve(ref) - } - }, [ - // Only create a new Observer instance if the ref or any of the options have been changed. - ref, - options.threshold, - options.root, - options.rootMargin, - options.triggerOnce, - ]) + return () => { + unobserve(ref) + } + }, + [ + // Only create a new Observer instance if the ref or any of the options have been changed. + ref, + options.threshold, + options.root, + options.rootMargin, + options.triggerOnce, + ], + ) React.useDebugValue(state.inView)