Skip to content

Commit 3dbe701

Browse files
committed
refactor(packages): @sa/hooks: use-request fir axios
1 parent e5cdcc9 commit 3dbe701

File tree

7 files changed

+48
-42
lines changed

7 files changed

+48
-42
lines changed

packages/hooks/src/index.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import useLoading from './use-loading';
33
import useCountDownTimer from './use-count-down';
44
import useSvgIconRender from './use-svg-icon-render';
55
import useHookTable from './use-table';
6-
export { useBoolean, useLoading, useCountDownTimer, useSvgIconRender, useHookTable };
6+
import useRequest from './use-request';
7+
export { useBoolean, useLoading, useCountDownTimer, useSvgIconRender, useHookTable, useRequest };
78

89
export * from './use-table';

packages/hooks/src/use-request/Fetch.ts

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,23 @@
11
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
22
// @ts-nocheck
33

4+
import type { FlatResponseData } from '@sa/axios';
5+
import type { AxiosError } from 'axios';
46
import type { MutableRefObject } from 'react';
57
import { isFunction } from './utils';
68
import type { FetchState, Options, PluginReturn, Service, Subscribe } from './type';
79

8-
export default class Fetch<TData, TParams extends any[]> {
10+
export default class Fetch<TData extends FlatResponseData, TParams extends any[]> {
911
pluginImpls: PluginReturn<TData, TParams>[];
1012

1113
count: number = 0;
1214

1315
state: FetchState<TData, TParams> = {
1416
loading: false,
1517
params: undefined,
18+
response: null,
1619
data: undefined,
17-
error: undefined
20+
error: null
1821
};
1922

2023
// eslint-disable-next-line max-params
@@ -86,36 +89,40 @@ export default class Fetch<TData, TParams extends any[]> {
8689
// const formattedResult = this.options.formatResultRef.current ? this.options.formatResultRef.current(res) : res;
8790

8891
this.setState({
89-
data: res,
90-
error: undefined,
92+
data: res.data,
93+
error: null,
94+
response: res.response,
9195
loading: false
9296
});
9397

94-
this.options.onSuccess?.(res, params);
98+
this.options.onSuccess?.(res.data, params);
9599
this.runPluginHandler('onSuccess', res, params);
96100

97-
this.options.onFinally?.(params, res, undefined);
101+
this.options.onFinally?.(params, res.data, null);
98102

99103
if (currentCount === this.count) {
100-
this.runPluginHandler('onFinally', params, res, undefined);
104+
this.runPluginHandler('onFinally', params, res, null);
101105
}
102106

103107
return res;
104108
} catch (error) {
109+
const errorMessage = error as AxiosError;
105110
if (currentCount !== this.count) {
106111
// prevent run.then when request is canceled
107112
return new Promise(() => {});
108113
}
109114

110115
this.setState({
111-
error,
116+
error: errorMessage,
117+
data: null,
118+
response: error.response,
112119
loading: false
113120
});
114121

115-
this.options.onError?.(error, params);
122+
this.options.onError?.(errorMessage, params);
116123
this.runPluginHandler('onError', error, params);
117124

118-
this.options.onFinally?.(params, undefined, error);
125+
this.options.onFinally?.(params, undefined, errorMessage);
119126

120127
if (currentCount === this.count) {
121128
this.runPluginHandler('onFinally', params, undefined, error);
@@ -150,7 +157,7 @@ export default class Fetch<TData, TParams extends any[]> {
150157
return this.runAsync(...(this.state.params || []));
151158
}
152159

153-
mutate(data?: TData | ((oldData?: TData) => TData | undefined)) {
160+
mutate(data?: TData | ((oldData: TData | null) => TData | null)) {
154161
const targetData = isFunction(data) ? data(this.state.data) : data;
155162
this.runPluginHandler('onMutate', targetData);
156163
this.setState({
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import useRequest from './useRequest';
2+
3+
export default useRequest;

packages/hooks/src/use-request/type.ts

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import type { DependencyList } from 'react';
2+
import type { FlatResponseData } from '@sa/axios';
3+
import type { AxiosError } from 'axios';
24
import type Fetch from './Fetch';
35
import type { CachedData } from './utils/cache';
46

@@ -7,19 +9,20 @@ export type Subscribe = () => void;
79

810
// for Fetch
911

10-
export interface FetchState<TData, TParams extends any[]> {
12+
export interface FetchState<TData extends FlatResponseData, TParams extends any[]> {
1113
loading: boolean;
1214
params?: TParams;
13-
data?: TData;
14-
error?: Error;
15+
response: TData['response'];
16+
data: null | TData['data'];
17+
error: AxiosError | null;
1518
}
1619

1720
export interface PluginReturn<TData, TParams extends any[]> {
1821
onBefore?: (params: TParams) =>
1922
| ({
2023
stopNow?: boolean;
2124
returnNow?: boolean;
22-
} & Partial<FetchState<TData, TParams>>)
25+
} & Partial<FetchState<FlatResponseData, TParams>>)
2326
| null;
2427

2528
onRequest?: (
@@ -30,25 +33,21 @@ export interface PluginReturn<TData, TParams extends any[]> {
3033
};
3134

3235
onSuccess?: (data: TData, params: TParams) => void;
33-
onError?: (e: Error, params: TParams) => void;
34-
onFinally?: (params: TParams, data?: TData, e?: Error) => void;
36+
onError?: (e: AxiosError, params: TParams) => void;
37+
onFinally?: (params: TParams, data?: TData, e?: AxiosError) => void;
3538
onCancel?: () => void;
3639
onMutate?: (data: TData) => void;
3740
}
3841

3942
// for useRequestImplement
4043

41-
export interface Options<TData, TParams extends any[]> {
44+
export interface Options<TData extends FlatResponseData, TParams extends any[]> {
4245
manual?: boolean;
43-
4446
onBefore?: (params: TParams) => void;
45-
onSuccess?: (data: TData, params: TParams) => void;
47+
onSuccess?: (data: TData['data'], params: TParams) => void;
4648
onError?: (e: Error, params: TParams) => void;
47-
// formatResult?: (res: any) => TData;
48-
onFinally?: (params: TParams, data?: TData, e?: Error) => void;
49-
49+
onFinally?: (params: TParams, data: TData['data'] | null, e: Error | null) => void;
5050
defaultParams?: TParams;
51-
5251
// refreshDeps
5352
refreshDeps?: DependencyList;
5453
refreshDepsAction?: () => void;
@@ -93,23 +92,12 @@ export interface Options<TData, TParams extends any[]> {
9392
// [key: string]: any;
9493
}
9594

96-
export type Plugin<TData, TParams extends any[]> = {
95+
export type Plugin<TData extends FlatResponseData, TParams extends any[]> = {
9796
(fetchInstance: Fetch<TData, TParams>, options: Options<TData, TParams>): PluginReturn<TData, TParams>;
9897
onInit?: (options: Options<TData, TParams>) => Partial<FetchState<TData, TParams>>;
9998
};
10099

101-
// for index
102-
// export type OptionsWithoutFormat<TData, TParams extends any[]> = Omit<Options<TData, TParams>, 'formatResult'>;
103-
104-
// export interface OptionsWithFormat<TData, TParams extends any[], TFormated, TTFormated extends TFormated = any> extends Omit<Options<TTFormated, TParams>, 'formatResult'> {
105-
// formatResult: (res: TData) => TFormated;
106-
// };
107-
108-
export interface Result<TData, TParams extends any[]> {
109-
loading: boolean;
110-
data?: TData;
111-
error?: Error;
112-
params: TParams | [];
100+
export interface Result<TData extends FlatResponseData, TParams extends any[]> extends FetchState<TData, TParams> {
113101
cancel: Fetch<TData, TParams>['cancel'];
114102
refresh: Fetch<TData, TParams>['refresh'];
115103
refreshAsync: Fetch<TData, TParams>['refreshAsync'];

packages/hooks/src/use-request/useRequest.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { FlatResponseData } from '@sa/axios';
12
import useAutoRunPlugin from './plugins/useAutoRunPlugin';
23
import useCachePlugin from './plugins/useCachePlugin';
34
import useDebouncePlugin from './plugins/useDebouncePlugin';
@@ -9,7 +10,7 @@ import useThrottlePlugin from './plugins/useThrottlePlugin';
910
import type { Options, Plugin, Service } from './type';
1011
import useRequestImplement from './useRequestImplement';
1112

12-
function useRequest<TData, TParams extends any[]>(
13+
function useRequest<TData extends FlatResponseData, TParams extends any[]>(
1314
service: Service<TData, TParams>,
1415
options?: Options<TData, TParams>,
1516
plugins?: Plugin<TData, TParams>[]

packages/hooks/src/use-request/useRequestImplement.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
import { useCreation, useLatest, useMemoizedFn, useMount, useUnmount, useUpdate } from 'ahooks';
2+
import type { FlatResponseData } from '@sa/axios';
23
import { isDev } from './utils';
34
import Fetch from './Fetch';
45
import type { Options, Plugin, Result, Service } from './type';
56

6-
function useRequestImplement<TData, TParams extends any[]>(
7+
function useRequestImplement<
8+
TData extends FlatResponseData<T, ResponseData>,
9+
TParams extends any[],
10+
T = any,
11+
ResponseData = any
12+
>(
713
service: Service<TData, TParams>,
814
options: Options<TData, TParams> = {},
915
plugins: Plugin<TData, TParams>[] = []
10-
) {
16+
): Result<TData, TParams> {
1117
const { manual = false, ready = true, ...rest } = options;
1218

1319
if (isDev) {

packages/hooks/src/use-request/utils/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ export const isFunction = (value: unknown): value is (...args: any) => any => ty
22

33
export const isBrowser = Boolean(typeof window !== 'undefined' && window.document && window.document.createElement);
44

5-
export const isDev = import.meta.env.NODE_ENV === 'development' || import.meta.env.env.NODE_ENV === 'test';
5+
export const isDev = import.meta.env.DEV;

0 commit comments

Comments
 (0)