Skip to content

Commit

Permalink
fix: reject lazy option for useWatch as well
Browse files Browse the repository at this point in the history
  • Loading branch information
hlysine committed May 31, 2023
1 parent 9881e52 commit 4f14ef7
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
34 changes: 33 additions & 1 deletion src/__tests__/core.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ describe('useWatchEffect', () => {
() => {
effectFn(counter.value);
},
// @ts-ignore
// @ts-expect-error - lazy is not a valid option
{ lazy: true }
)
);
Expand Down Expand Up @@ -725,4 +725,36 @@ describe('useWatch', () => {
// expect the hook to warn about using it inside a component that is not wrapped by makeReactive
expect(consoleLog).toHaveBeenCalled();
});
it('is reactive', () => {
const counter = ref(1);
const effectFn = jest.fn();

const { unmount } = renderHook(() =>
useWatch(
counter,
(...args) => {
effectFn(...args);
},
// @ts-expect-error - lazy is not a valid option
{ lazy: true }
)
);

expect(effectFn).toBeCalledTimes(0);

act(() => {
counter.value++;
});

expect(effectFn).toBeCalledTimes(1);

unmount();
act(() => {
counter.value++;
});

expect(effectFn).toBeCalledTimes(1);

expect(consoleWarn).toBeCalled();
});
});
8 changes: 7 additions & 1 deletion src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -586,9 +586,15 @@ export const useWatch: UseWatchOverloads = <
cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>,
options?: WatchOptions<Immediate>
): void => {
if (options && 'lazy' in options && options.lazy) {
messages.warnLazyWatch();
}
const reactiveRef = useRef<WatchStopHandle | null>(null);
if (reactiveRef.current === null) {
reactiveRef.current = watch(sources, cb, options);
reactiveRef.current = watch(sources, cb, {
...options,
lazy: false,
} as WatchOptions<Immediate>);
if (getCurrentScope() !== undefined) {
onScopeDispose(() => {
reactiveRef.current = null;
Expand Down
7 changes: 7 additions & 0 deletions src/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ const messages = {
'Use watchEffect if you want to control the execution timing of the effect.'
);
},
warnLazyWatch() {
console.warn(
'"lazy" option is not supported for useWatch because the effect has to be run to collect dependencies. ' +
'Use the "immediate" option if you want to control callback execution. ' +
'Use watch if you want to control the execution timing of the effect.'
);
},
warnInvalidWatchSource(s: unknown) {
console.warn(
'Invalid watch source: ',
Expand Down

0 comments on commit 4f14ef7

Please sign in to comment.