Skip to content

Commit b210f5c

Browse files
committed
feat: ready supports passing functions #166
1 parent ceb4302 commit b210f5c

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

src/__tests__/index.test.tsx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,42 @@ describe('useRequest', () => {
510510
expect(wrapper.data).toBe('run');
511511
});
512512

513+
test('ready should work when ready is a function', async () => {
514+
const count = 0;
515+
const wrapper = mount(
516+
defineComponent({
517+
template: '<div/>',
518+
setup() {
519+
const count = ref(0);
520+
const { loading } = useRequest(request, {
521+
ready: () => count.value >= 2,
522+
});
523+
524+
const handleUpdateCount = () => {
525+
count.value += 1;
526+
};
527+
528+
return {
529+
loading,
530+
handleUpdateCount,
531+
};
532+
},
533+
}),
534+
);
535+
await waitForAll();
536+
wrapper.handleUpdateCount();
537+
expect(wrapper.loading).toBe(false);
538+
await waitForAll();
539+
540+
wrapper.handleUpdateCount();
541+
expect(wrapper.loading).toBe(true);
542+
await waitForAll();
543+
544+
wrapper.handleUpdateCount();
545+
expect(wrapper.loading).toBe(false);
546+
await waitForAll();
547+
});
548+
513549
test('track ready when ready initial value is true', async () => {
514550
const wrapper = mount(
515551
defineComponent({

src/core/plugins/useReadyPlugin.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { ref, watch } from 'vue-demi';
22

33
import { definePlugin } from '../definePlugin';
4+
import { isFunction } from '../utils';
45

56
export default definePlugin(
67
(queryInstance, { ready = ref(true), manual, defaultParams = [] }) => {
@@ -18,7 +19,8 @@ export default definePlugin(
1819
);
1920
return {
2021
onBefore() {
21-
if (!ready.value) {
22+
const readyFlag = isFunction(ready) ? ready() : ready.value;
23+
if (!readyFlag) {
2224
queryInstance.loading.value = false;
2325
return {
2426
isBreak: true,

src/core/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ export type BaseOptions = {
7373

7474
export type Options<R, P extends unknown[]> = BaseOptions & {
7575
defaultParams?: P;
76-
ready?: Ref<boolean>;
76+
ready?: Ref<boolean> | (() => boolean);
7777
initialData?: R;
7878
refreshDeps?: WatchSource | WatchSource[];
7979
cacheKey?: string | ((params?: P) => string);

0 commit comments

Comments
 (0)