Skip to content

Commit e62edde

Browse files
authored
fix: use-request auto deps refresh plugins invalid
fix: use-request auto deps refresh plugins invalid
2 parents 86dd14a + 2aa1bdd commit e62edde

File tree

14 files changed

+225
-89
lines changed

14 files changed

+225
-89
lines changed

package.json

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@
1313
"test": "vitest",
1414
"test:ui": "vitest --ui",
1515
"coverage": "vitest run --coverage",
16-
"prepare": "husky install",
17-
"build:types": "cd packages/hooks && vue-tsc --noEmit && vite build --mode fullTypes"
16+
"prepare": "husky install"
1817
},
1918
"devDependencies": {
2019
"@commitlint/cli": "^17.1.2",
@@ -63,10 +62,10 @@
6362
"tsx": "^3.11.0",
6463
"typeit": "^8.7.0",
6564
"typescript": "^4.9.3",
66-
"vite": "3.0.2",
67-
"vite-plugin-build": "0.6.0",
68-
"vite-plugin-dts": "^1.4.1",
69-
"vitepress": "1.0.0-alpha.4",
65+
"vite": "^4.0.3",
66+
"vite-plugin-build": "0.7.1",
67+
"vite-plugin-dts": "^2.1.0",
68+
"vitepress": "1.0.0-alpha.60",
7069
"vitest": "0.25.3",
7170
"vue": "^3.2.25",
7271
"vue-tsc": "1.0.9",

packages/hooks/src/useRequest/Fetch.ts

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Ref, unref, watchEffect } from 'vue'
1+
import { Ref } from 'vue'
22
import {
33
UseRequestFetchState,
44
UseRequestOptions,
@@ -107,7 +107,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
107107
)
108108
// 是否停止请求
109109
if (stopNow) {
110-
return new Promise(() => {})
110+
return new Promise(() => { })
111111
}
112112

113113
this.setState({
@@ -131,7 +131,7 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
131131
const requestReturnResponse = (res: any) => {
132132
// 取消了请求,count将与currentCount不一致,将发送空请求
133133
if (currentCount !== this.count) {
134-
return new Promise(() => {})
134+
return new Promise(() => { })
135135
}
136136
// 格式化数据
137137
const formattedResult = this.options.formatResult ? this.options.formatResult(res) : res
@@ -158,24 +158,26 @@ export default class Fetch<TData, TParams extends unknown[] = any> {
158158

159159
if (!servicePromise) {
160160
/** 自动依赖收集 */
161-
if (!this.options.manual && this.options.refreshDeps === true) {
162-
watchEffect(async () => {
163-
if (unref(this.options.ready)) {
164-
this.setFetchState(true, 'loading')
165-
servicePromise = this.serviceRef.value(...params)
166-
const servicePromiseResult = await servicePromise
167-
return requestReturnResponse(servicePromiseResult)
168-
}
169-
})
170-
} else {
171-
servicePromise = this.serviceRef.value(...params)
172-
}
161+
// if (!this.options.manual && this.options.refreshDeps === true) {
162+
// watchEffect(async () => {
163+
// if (unref(this.options.ready)) {
164+
// this.setFetchState(true, 'loading')
165+
// servicePromise = this.serviceRef.value(...params)
166+
// const servicePromiseResult = await servicePromise
167+
// return requestReturnResponse(servicePromiseResult)
168+
// }
169+
// })
170+
// } else {
171+
// servicePromise = this.serviceRef.value(...params)
172+
// }
173+
servicePromise = this.serviceRef.value(...params)
173174
}
175+
// servicePromise = this.serviceRef.value(...params)
174176
const servicePromiseResult = await servicePromise
175177
return requestReturnResponse(servicePromiseResult)
176178
} catch (error) {
177179
if (currentCount !== this.count) {
178-
return new Promise(() => {})
180+
return new Promise(() => { })
179181
}
180182

181183
this.setState({

packages/hooks/src/useRequest/docs/cache/demo/demo4.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
staleTime: 5000,
2828
2929
setCache: res => {
30-
localStorage.setItem(cacheKey, `${res.data}`)
30+
localStorage.setItem(cacheKey, JSON.stringify(res.data))
3131
},
3232
getCache: () => {
3333
return JSON.parse(localStorage.getItem(cacheKey) ?? '{}')

packages/hooks/src/useRequest/docs/global/demo/demo.vue

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,15 @@
3535
}, 1000)
3636
})
3737
}
38-
const { data, loading } = useRequest(() => getUsername({ desc: 'good' }))
38+
const { data, loading } = useRequest(() => getUsername({ desc: 'good' }), {
39+
// manual: true,
40+
onSuccess: res => {
41+
// debugger
42+
console.log(res)
43+
},
44+
})
45+
46+
// run()
3947
return () => {
4048
return h('div', {}, [
4149
h('h3', 'demo2'),

packages/hooks/src/useRequest/docs/refreshDeps/demo/demo1.vue

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@
5858
storeId: number | string
5959
count: number | string
6060
}> {
61+
console.log('request')
62+
6163
return new Promise(resolve => {
6264
setTimeout(() => {
6365
resolve({
@@ -75,7 +77,7 @@
7577
})
7678
const count = ref(0)
7779
78-
const ready = computed(() => count.value !== 0 && count.value !== 5)
80+
const ready = computed(() => count.value !== undefined)
7981
const { data, loading } = useRequest(
8082
() => getUsername({ id: id.value, storeId: store.id, count: count.value }),
8183
{
@@ -87,6 +89,7 @@
8789
},
8890
ready,
8991
refreshDeps: true,
92+
debounceWait: 1000,
9093
},
9194
)
9295
</script>

packages/hooks/src/useRequest/plugins/usePollingPlugin.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ const usePollingPlugin: UseRequestPlugin<unknown, unknown[]> = (
1010
const timerRef = ref<Interval>();
1111
const unsubscribeRef = ref<() => void>();
1212
const countRef = ref<number>(0);
13-
13+
14+
1415

1516
const stopPolling = () => {
1617
if (timerRef.value) {
@@ -33,7 +34,7 @@ const usePollingPlugin: UseRequestPlugin<unknown, unknown[]> = (
3334
onBefore: () => {
3435
stopPolling();
3536
},
36-
onError: () => {
37+
onError: () => {
3738
countRef.value += 1;
3839
},
3940
onSuccess: () => {

packages/hooks/src/useRequest/useRequestImplement.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ref, reactive, toRefs, onMounted, onUnmounted, unref, inject, UnwrapRef } from 'vue'
1+
import { ref, reactive, toRefs, onUnmounted, inject, UnwrapRef, watchEffect, computed, isRef, onMounted, unref } from 'vue'
22

33
import Fetch from './Fetch'
44
import { USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY } from './config'
@@ -89,6 +89,27 @@ function useRequestImplement<TData, TParams extends any[]>(
8989
return p(fetchInstance, fetchOptions)
9090
})
9191

92+
const readyComputed = computed(() => isRef(ready) ? ready.value : ready)
93+
94+
// const isMount = ref(false)
95+
96+
watchEffect(() => {
97+
if (!manual) {
98+
const params = fetchInstance.state.params || options.defaultParams || []
99+
// if (readyComputed.value && !isMount.value) {
100+
// fetchInstance.run(...(params as TParams))
101+
// // 模拟首次mount
102+
// isMount.value = true
103+
104+
// }
105+
// 自动收集依赖
106+
if (readyComputed.value && fetchInstance.options.refreshDeps === true && !!serviceRef.value) {
107+
console.log("运行1");
108+
fetchInstance.run(...(params as TParams))
109+
}
110+
}
111+
})
112+
92113
// manual
93114
onMounted(() => {
94115
if (!manual) {

packages/hooks/src/useWebSocket/demo/demo.vue

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
const { readyState, sendMessage, latestMessage, disconnect, connect } = useWebSocket(
4242
'wss://demo.piesocket.com/v3/channel_1?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV&notify_self',
4343
)
44-
const messageHistory = computed(() => latestMessage?.value)
44+
const messageHistory = computed(() => latestMessage.value)
4545
4646
const messageList = ref<any[]>([])
4747

packages/hooks/src/useWebSocket/index.ts

Lines changed: 32 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/* eslint-disable no-unused-vars */
2-
import { watch, ref, Ref, onUnmounted, unref } from 'vue'
2+
import { watch, ref, Ref, onUnmounted, unref, isRef } from 'vue'
33

44
export enum ReadyState {
55
Connecting = 0,
@@ -21,7 +21,7 @@ export interface UseWebSocketOptions {
2121
}
2222

2323
export interface UseWebSocketResult {
24-
latestMessage?: Ref<WebSocketEventMap['message']>
24+
latestMessage: Ref<WebSocketEventMap['message'] | undefined>
2525
sendMessage?: WebSocket['send']
2626
disconnect?: () => void
2727
connect?: () => void
@@ -144,18 +144,36 @@ export default function useWebSocket(
144144
websocketRef.value?.close()
145145
}
146146

147-
watch(
148-
[socketUrl, manual],
149-
c => {
150-
const [_, manualWatch] = c
151-
if (!manualWatch) {
152-
connect()
153-
}
154-
},
155-
{
156-
immediate: true,
157-
},
158-
)
147+
if (isRef(socketUrl) && isRef(manual))
148+
watch(
149+
[socketUrl, manual],
150+
c => {
151+
const [_, manualWatch] = c
152+
if (!manualWatch) {
153+
connect()
154+
}
155+
},
156+
{
157+
immediate: true,
158+
},
159+
)
160+
else if (isRef(manual)) {
161+
watch(
162+
manual,
163+
manualWatch => {
164+
if (!manualWatch) {
165+
connect()
166+
}
167+
},
168+
{
169+
immediate: true,
170+
},
171+
)
172+
} else {
173+
if (!manual) {
174+
connect()
175+
}
176+
}
159177

160178
onUnmounted(() => {
161179
unmountedRef.value = true

packages/hooks/vite.config.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { defineConfig } from 'vite'
2-
import { buildConfig, buildFullTypesConfig } from './scripts/build'
2+
import { buildConfig } from './scripts/build'
33
// import config from './scripts/config'
44

5-
export default defineConfig(({ mode }) => {
6-
if (mode === 'fullTypes') {
7-
return buildFullTypesConfig
8-
}
5+
export default defineConfig(() => {
6+
// if (mode === 'fullTypes') {
7+
// return buildFullTypesConfig
8+
// }
99
return buildConfig
1010
})

packages/types/index.d.ts

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ declare interface CachedData<TData = any, TParams = any> {
1717
time: number;
1818
}
1919

20-
export declare const clearCache: (key?: string | string[]) => void;
20+
export declare const clearUseRequestCache: (key?: string | string[]) => void;
21+
22+
export declare function createUseRequest<TData, TParams extends unknown[] = unknown[], PluginsOptions extends UseRequestPlugin<TData, TParams>[] = UseRequestPlugin<TData, TParams>[]>(service: UseRequestService<TData, TParams>, options?: UseRequestOptions<TData, TParams, PluginsOptions extends (infer P)[] ? P extends UseRequestPlugin<TData, TParams, infer R> ? R : any : any>, plugins?: PluginsOptions): useRequestResult<TData, TParams>;
2123

2224
declare interface DebounceOptions {
2325
/**
@@ -66,20 +68,26 @@ declare const eventEmitterOverall: EventEmitter<unknown>;
6668
declare class Fetch<TData, TParams extends unknown[] = any> {
6769
serviceRef: Ref<UseRequestService<TData, TParams>>;
6870
options: UseRequestOptions<TData, TParams, any>;
69-
setUpdateData: (s: any, key?: keyof UseRequestFetchState<TData, TParams>) => void;
71+
setUpdateData: (currentState: unknown, key?: keyof UseRequestFetchState<TData, TParams>) => void;
7072
initState: Partial<UseRequestFetchState<TData, TParams>>;
7173
pluginImpls: UseRequestPluginReturn<TData, TParams>[] | undefined;
7274
count: number;
7375
state: UseRequestFetchState<TData, TParams>;
74-
constructor(serviceRef: Ref<UseRequestService<TData, TParams>>, options: UseRequestOptions<TData, TParams, any>, setUpdateData: (s: any, key?: keyof UseRequestFetchState<TData, TParams>) => void, initState?: Partial<UseRequestFetchState<TData, TParams>>);
75-
setState(s?: Partial<UseRequestFetchState<TData, TParams>>): void;
76+
constructor(serviceRef: Ref<UseRequestService<TData, TParams>>, options: UseRequestOptions<TData, TParams, any>, setUpdateData: (currentState: unknown, key?: keyof UseRequestFetchState<TData, TParams>) => void, initState?: Partial<UseRequestFetchState<TData, TParams>>);
77+
setState(currentState?: Partial<UseRequestFetchState<TData, TParams>>): void;
78+
/**
79+
* should rename
80+
* @param data Result value `unknown`
81+
* @param key Result key `data`| `params` | `loading`| `error`
82+
*/
83+
setData(data: unknown, key?: keyof UseRequestFetchState<TData, TParams> | (keyof UseRequestFetchState<TData, TParams>)[]): void;
7684
/**
7785
*
78-
* @param data Result value `any`
86+
* @param data Result value `unknown`
7987
* @param key Result key `data`| `params` | `loading`| `error`
8088
*/
81-
setData(data: any, key?: keyof UseRequestFetchState<TData, TParams> | (keyof UseRequestFetchState<TData, TParams>)[]): void;
82-
runPluginHandler(event: keyof UseRequestPluginReturn<TData, TParams>, ...rest: any[]): any;
89+
setFetchState(data: unknown, key?: keyof UseRequestFetchState<TData, TParams> | (keyof UseRequestFetchState<TData, TParams>)[]): void;
90+
runPluginHandler(event: keyof UseRequestPluginReturn<TData, TParams>, ...rest: unknown[]): any;
8391
runAsync(...params: TParams): Promise<TData>;
8492
run(...params: TParams): void;
8593
cancel(): void;
@@ -216,7 +224,7 @@ declare interface UseBooleanActions {
216224

217225
declare type UseBooleanResult = [Ref<boolean>, UseBooleanActions];
218226

219-
export declare function useCookieState(cookieKey: string, options?: UseCookieStateOptions): readonly [Ref<UseCookieStateType>, (newValue: UseCookieStateType | ((prevState: UseCookieStateType) => UseCookieStateType), newOptions?: Cookies.CookieAttributes) => void];
227+
export declare function useCookieState(cookieKey: string, options?: UseCookieStateOptions): readonly [any, (newValue: UseCookieStateType | ((prevState: UseCookieStateType) => UseCookieStateType), newOptions?: Cookies.CookieAttributes) => void];
220228

221229
declare interface UseCookieStateOptions extends Cookies.CookieAttributes {
222230
defaultValue?: UseCookieStateType | (() => UseCookieStateType);
@@ -925,6 +933,8 @@ declare interface UseRequestPluginReturn<TData, TParams extends unknown[]> {
925933
onMutate?: (data: TData) => void;
926934
}
927935

936+
export declare function useRequestProvider(config: UseRequestOptions<unknown, any, any>): void;
937+
928938
declare interface useRequestResult<TData, TParams extends unknown[]> {
929939
/**
930940
* Is the service being executed.
@@ -990,7 +1000,7 @@ declare interface UseSetActions<T> {
9901000

9911001
export declare function useSetState<S extends Record<string, any>>(initialState: UseSetStateType<S>): [
9921002
DeepReadonly<UnwrapNestedRefs<[S] extends [Ref<any>] ? S : Ref<UnwrapRef<S>>>>,
993-
(patch: Record<string, any>) => void
1003+
(patch: Record<string, any>, cover?: boolean) => void
9941004
];
9951005

9961006
declare type UseSetStateType<S> = S | (() => S) | Ref<S> | (() => Ref<S>);
@@ -1090,7 +1100,7 @@ declare type UseSetStateType<S> = S | (() => S) | Ref<S> | (() => Ref<S>);
10901100
}
10911101

10921102
declare interface UseWebSocketResult {
1093-
latestMessage?: Ref<WebSocketEventMap['message']>;
1103+
latestMessage: Ref<WebSocketEventMap['message'] | undefined>;
10941104
sendMessage?: WebSocket['send'];
10951105
disconnect?: () => void;
10961106
connect?: () => void;

packages/types/tsconfig.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
"extends": "../../tsconfig.json",
33
"compilerOptions": {
44
"outDir": "./dist", //输出文件
5-
"lib": ["esnext", "dom"]
5+
"lib": ["esnext", "dom"],
66
// "baseUrl": "../hooks",
7-
// "rootDir": "../hooks"
7+
"rootDir": "../hooks/src"
88
},
99
"include": ["../hooks/src/**/*.ts"],
1010
"exclude": ["node_modules", "dist", "lib", "es", "example", "test-utils/*"]

packages/types/vite.config.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ export default defineConfig({
77
dts({
88
include: ['../hooks/src/**/*.ts'],
99
outputDir: path.resolve(__dirname),
10+
tsConfigFilePath: './tsconfig.json',
1011
rollupTypes: true,
1112
}),
1213
],

0 commit comments

Comments
 (0)