Skip to content

Commit 7204a88

Browse files
committed
fix: throw error if trying to Observe already observed element
1 parent 07dc223 commit 7204a88

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

src/__tests__/intersection.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@ it('should observe', () => {
2323
})
2424
})
2525

26+
it('should throw error if already observering', () => {
27+
const cb = jest.fn()
28+
observe(el, cb)
29+
expect(() => observe(el, cb)).toThrowError()
30+
})
31+
2632
it('should observe with options', () => {
2733
const cb = jest.fn()
2834
const instance = observe(el, cb, { threshold: 0 })

src/intersection.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// @flow
2+
import invariant from 'invariant'
3+
24
type Callback = (inView: boolean) => void
35

46
type Instance = {
@@ -30,6 +32,12 @@ export function observe(
3032
},
3133
rootId?: string,
3234
) {
35+
// Validate that the element is not being used in another <Observer />
36+
invariant(
37+
!INSTANCE_MAP.has(element),
38+
"react-intersection-observer: Trying to observe %s, but it's already being observed by another instance.\nMake sure the `ref` is only used by a single <Observer /> instance.\n\n%s",
39+
element,
40+
)
3341
const { root, rootMargin } = options
3442
const threshold = options.threshold || 0
3543
if (!element || !callback) return

0 commit comments

Comments
 (0)