fix(useIntersection): disconnect an old IntersectionObserver instance when the ref changes

This commit is contained in:
dizel3d 2020-01-27 23:52:48 +03:00
parent f06895d9d5
commit ac2f54a8f6
2 changed files with 22 additions and 6 deletions

View File

@ -15,14 +15,10 @@ const useIntersection = (
const observer = new IntersectionObserver(handler, options);
observer.observe(ref.current);
return () => {
if (ref.current) {
observer.disconnect();
}
};
return () => observer.disconnect();
}
return () => {};
}, [ref, options.threshold, options.root, options.rootMargin]);
}, [ref.current, options.threshold, options.root, options.rootMargin]);
return intersectionObserverEntry;
};

View File

@ -8,6 +8,10 @@ import { useIntersection } from '../src';
beforeEach(() => {
intersectionObserver.mock();
const IO = IntersectionObserver;
jest.spyOn(IO.prototype, 'disconnect');
jest.spyOn(global as any, 'IntersectionObserver');
IntersectionObserver.prototype = IO.prototype;
});
afterEach(() => {
@ -45,6 +49,22 @@ describe('useIntersection', () => {
expect(result.current).toBe(null);
});
it('should disconnect an old IntersectionObserver instance when the ref changes', () => {
targetRef = createRef();
targetRef.current = document.createElement('div');
const { rerender } = renderHook(() => useIntersection(targetRef, {}));
targetRef.current = document.createElement('div');
rerender();
targetRef.current = null;
rerender();
expect(IntersectionObserver).toHaveBeenCalledTimes(2);
expect(IntersectionObserver.prototype.disconnect).toHaveBeenCalledTimes(2);
});
it('should return the first IntersectionObserverEntry when the IntersectionObserver registers an intersection', () => {
TestUtils.act(() => {
targetRef = createRef();