Skip to content

Commit

Permalink
fix(useIntersection): disconnect an old IntersectionObserver instance…
Browse files Browse the repository at this point in the history
… when the ref changes
  • Loading branch information
dizel3d committed Jan 27, 2020
1 parent f06895d commit ac2f54a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
8 changes: 2 additions & 6 deletions src/useIntersection.ts
Expand Up @@ -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;
};
Expand Down
20 changes: 20 additions & 0 deletions tests/useIntersection.test.tsx
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit ac2f54a

Please sign in to comment.