Skip to content

Commit

Permalink
fix(useIntersection): reset an intersectionObserverEntry when the ref…
Browse files Browse the repository at this point in the history
… changes
  • Loading branch information
dizel3d committed Jan 27, 2020
1 parent ac2f54a commit 3f8687e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/useIntersection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ const useIntersection = (
const observer = new IntersectionObserver(handler, options);
observer.observe(ref.current);

return () => observer.disconnect();
return () => {
setIntersectionObserverEntry(null);
observer.disconnect();
};
}
return () => {};
}, [ref.current, options.threshold, options.root, options.rootMargin]);
Expand Down
29 changes: 29 additions & 0 deletions tests/useIntersection.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,35 @@ describe('useIntersection', () => {
expect(result.current).toBe(null);
});

it('should reset an intersectionObserverEntry when the ref changes', () => {
TestUtils.act(() => {
targetRef = createRef();
ReactDOM.render(<div ref={targetRef} />, container);
});

const { result, rerender } = renderHook(() => useIntersection(targetRef, { root: container, threshold: 0.8 }));

const mockIntersectionObserverEntry = {
boundingClientRect: targetRef.current.getBoundingClientRect(),
intersectionRatio: 0.81,
intersectionRect: container.getBoundingClientRect(),
isIntersecting: true,
rootBounds: container.getBoundingClientRect(),
target: targetRef.current,
time: 300,
};
TestRenderer.act(() => {
intersectionObserver.simulate(mockIntersectionObserverEntry);
});

expect(result.current).toEqual(mockIntersectionObserverEntry);

targetRef.current = document.createElement('div');
rerender();

expect(result.current).toEqual(null);
});

it('should disconnect an old IntersectionObserver instance when the ref changes', () => {
targetRef = createRef();
targetRef.current = document.createElement('div');
Expand Down

0 comments on commit 3f8687e

Please sign in to comment.