Skip to content

Commit

Permalink
fix: useInViewport support once API
Browse files Browse the repository at this point in the history
  • Loading branch information
LingJinT committed Apr 28, 2024
1 parent 6bec34c commit 1f69533
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
19 changes: 19 additions & 0 deletions packages/hooks/src/useInViewport/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,23 @@ describe('useInViewport', () => {
unmount();
expect(disconnect).toBeCalled();
});

it('should work once when props once is true', async () => {
const { result } = renderHook(() => useInViewport(targetEl, { once: true }));
const calls = mockIntersectionObserver.mock.calls;
const [onChange] = calls[calls.length - 1];

act(() => {
onChange([{ targetEl, isIntersecting: true, intersectionRatio: 0.5 }]);
});
const [inViewport, ratio] = result.current;
expect(inViewport).toBeTruthy();
expect(ratio).toBe(0.5);

act(() => {
onChange([{ targetEl, isIntersecting: false, intersectionRatio: 0 }]);
});
expect(inViewport).toBeTruthy();
expect(ratio).toBe(0.5);
});
});
6 changes: 5 additions & 1 deletion packages/hooks/src/useInViewport/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ export interface Options {
threshold?: number | number[];
root?: BasicTarget<Element>;
callback?: CallbackType;
once?: boolean;
}

function useInViewport(target: BasicTarget | BasicTarget[], options?: Options) {
const { callback, ...option } = options || {};
const { callback, once, ...option } = options || {};

const [state, setState] = useState<boolean>();
const [ratio, setRatio] = useState<number>();
Expand All @@ -35,6 +36,9 @@ function useInViewport(target: BasicTarget | BasicTarget[], options?: Options) {
setState(entry.isIntersecting);
callback?.(entry);
}
if (once) {
observer.disconnect();
}
},
{
...option,
Expand Down

0 comments on commit 1f69533

Please sign in to comment.