Skip to content

Commit

Permalink
chore: add onCancel for useRequest
Browse files Browse the repository at this point in the history
  • Loading branch information
qrliu97 committed Dec 6, 2024
1 parent c7bb04c commit d7ec8fe
Show file tree
Hide file tree
Showing 5 changed files with 8 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/hooks/src/useRequest/doc/basic/basic.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Next, we will demonstrate the difference between `run` and `runAsync` through th
- `onSuccess`: Triggered when the request is resolved
- `onError`: Triggered when the request is rejected
- `onFinally`: Triggered when the request is completed
- `onCancel`: Triggered when the request is canceled

<code src="./demo/lifeCycle.tsx" />

Expand Down
1 change: 1 addition & 0 deletions packages/hooks/src/useRequest/doc/basic/basic.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const { loading, run, runAsync } = useRequest(service, {
- `onSuccess`:请求成功触发
- `onError`:请求失败触发
- `onFinally`:请求完成触发
- `onCancel`:请求取消触发

<code src="./demo/lifeCycle.tsx" />

Expand Down
5 changes: 4 additions & 1 deletion packages/hooks/src/useRequest/src/Fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,15 @@ export default class Fetch<TData, TParams extends any[]> {
});
}

cancel() {
cancel(isUnmount = false) {
this.count += 1;
this.setState({
loading: false,
});

if(!isUnmount){
this.options.onCancel?.();
}
this.runPluginHandler('onCancel');
}

Expand Down
1 change: 1 addition & 0 deletions packages/hooks/src/useRequest/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export interface Options<TData, TParams extends any[]> {
onError?: (e: Error, params: TParams) => void;
// formatResult?: (res: any) => TData;
onFinally?: (params: TParams, data?: TData, e?: Error) => void;
onCancel?: () => void;

defaultParams?: TParams;

Expand Down
2 changes: 1 addition & 1 deletion packages/hooks/src/useRequest/src/useRequestImplement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function useRequestImplement<TData, TParams extends any[]>(
});

useUnmount(() => {
fetchInstance.cancel();
fetchInstance.cancel(true);
});

return {
Expand Down

0 comments on commit d7ec8fe

Please sign in to comment.