Skip to content

Commit 2d5d541

Browse files
committed
fix: respect threshold before trigger once cleanup
1 parent b97fbaa commit 2d5d541

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎src/__tests__/useInView.test.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,38 @@ test("should respect trigger once", () => {
118118
getByText("true");
119119
});
120120

121+
test("should respect the threshold before triggering once", () => {
122+
const { getByTestId, getByText } = render(
123+
<HookComponent
124+
options={{ initialInView: true, threshold: 0.5, triggerOnce: true }}
125+
/>,
126+
);
127+
const wrapper = getByTestId("wrapper");
128+
const instance = intersectionMockInstance(wrapper);
129+
const callback = vi.mocked(window.IntersectionObserver).mock.calls[0][0];
130+
const createEntry = (
131+
intersectionRatio: number,
132+
): IntersectionObserverEntry => ({
133+
boundingClientRect: wrapper.getBoundingClientRect(),
134+
intersectionRatio,
135+
intersectionRect: wrapper.getBoundingClientRect(),
136+
isIntersecting: true,
137+
rootBounds: null,
138+
target: wrapper,
139+
time: performance.now(),
140+
});
141+
142+
React.act(() => callback([createEntry(0.25)], instance));
143+
144+
getByText("false");
145+
expect(instance.unobserve).not.toHaveBeenCalled();
146+
147+
React.act(() => callback([createEntry(0.5)], instance));
148+
149+
getByText("true");
150+
expect(instance.unobserve).toHaveBeenCalledTimes(1);
151+
});
152+
121153
test("should trigger onChange", () => {
122154
const onChange = vi.fn();
123155
render(<HookComponent options={{ onChange }} />);

‎src/useInView.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ export function useInView({
8585
});
8686
if (callback.current) callback.current(inView, entry);
8787

88-
if (entry.isIntersecting && triggerOnce && unobserve) {
88+
if (inView && triggerOnce && unobserve) {
8989
// If it should only trigger once, unobserve the element after it's inView
9090
unobserve();
9191
unobserve = undefined;

0 commit comments

Comments
 (0)