From 4f6d3887be5cf62ce42357a7bf27f4ae8b080eba Mon Sep 17 00:00:00 2001 From: dizel3d Date: Tue, 28 Jan 2020 00:25:11 +0300 Subject: [PATCH] fix(useIntersection): return null if IntersectionObserver is not supported --- src/useIntersection.ts | 2 +- tests/useIntersection.test.tsx | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/src/useIntersection.ts b/src/useIntersection.ts index aec578f4..7cf9941d 100644 --- a/src/useIntersection.ts +++ b/src/useIntersection.ts @@ -7,7 +7,7 @@ const useIntersection = ( const [intersectionObserverEntry, setIntersectionObserverEntry] = useState(null); useEffect(() => { - if (ref.current) { + if (ref.current && typeof IntersectionObserver === 'function') { const handler = (entries: IntersectionObserverEntry[]) => { setIntersectionObserverEntry(entries[0]); }; diff --git a/tests/useIntersection.test.tsx b/tests/useIntersection.test.tsx index cdd3d9e8..bdb7bc05 100644 --- a/tests/useIntersection.test.tsx +++ b/tests/useIntersection.test.tsx @@ -78,6 +78,14 @@ describe('useIntersection', () => { expect(result.current).toEqual(null); }); + it('should return null if IntersectionObserver is not supported', () => { + targetRef = createRef(); + targetRef.current = document.createElement('div'); + delete window.IntersectionObserver; + + expect(() => renderHook(() => useIntersection(targetRef, {}))).not.toThrow(); + }); + it('should disconnect an old IntersectionObserver instance when the ref changes', () => { targetRef = createRef(); targetRef.current = document.createElement('div');