mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
fix(useIntersection): disconnect an old IntersectionObserver instance when the ref changes
This commit is contained in:
parent
f06895d9d5
commit
ac2f54a8f6
@ -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;
|
||||
};
|
||||
|
||||
@ -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();
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user