fix(useIntersection): reset an intersectionObserverEntry when the ref changes

This commit is contained in:
dizel3d 2020-01-28 00:24:34 +03:00
parent ac2f54a8f6
commit 3f8687e1f5
2 changed files with 33 additions and 1 deletions

View File

@ -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]);

View File

@ -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');