Skip to content

Commit d40c7a9

Browse files
authored
Merge pull request #13 from axios-use/feat-return-all-response
Feat: return all response
2 parents f6a2611 + a6c5cfa commit d40c7a9

7 files changed

+46
-33
lines changed

README.md

+6-6
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ const [createRequest, { hasPending, cancel }] = useRequest((id: string) =>
105105
```tsx
106106
interface CreateRequest {
107107
// Promise function
108-
ready: () => Promise<[Payload<TRequest>, AxiosRestResponse]>;
108+
ready: () => Promise<[Payload<TRequest>, AxiosResponse]>;
109109
// Axios Canceler. clear current request.
110110
cancel: Canceler;
111111
}
@@ -138,7 +138,7 @@ const [createRequest, { hasPending, cancel }] = useRequest(
138138
method: "DELETE",
139139
}),
140140
{
141-
onCompleted: (data, other) => console.info(data, other),
141+
onCompleted: (data, response) => console.info(data, response),
142142
onError: (err) => console.info(err),
143143
},
144144
);
@@ -154,7 +154,7 @@ const [createRequest, { hasPending, cancel }] = useRequest(
154154
| options.cacheKey | string\| number \| function | Custom cache key value |
155155
| options.cacheFilter | function | Callback function to decide whether to cache or not |
156156
| options.filter | function | Request filter. if return a falsy value, will not start the request |
157-
| options.defaultState | object | Initialize the state value. `{data, other, error, isLoading}` |
157+
| options.defaultState | object | Initialize the state value. `{data, response, error, isLoading}` |
158158
| options.onCompleted | function | This function is passed the query's result data. |
159159
| options.onError | function | This function is passed an `RequestError` object |
160160
| options.instance | `AxiosInstance` | Customize the Axios instance of the current item |
@@ -180,8 +180,8 @@ const [reqState, fetch] = useResource((id: string) =>
180180
interface ReqState {
181181
// Result
182182
data?: Payload<TRequest>;
183-
// other axios response. Omit<AxiosResponse, "data">
184-
other?: AxiosRestResponse;
183+
// axios response
184+
response?: AxiosResponse;
185185
// normalized error
186186
error?: RequestError<Payload<TRequest>>;
187187
isLoading: boolean;
@@ -235,7 +235,7 @@ const [reqState] = useResource(
235235
}),
236236
[],
237237
{
238-
onCompleted: (data, other) => console.info(data, other),
238+
onCompleted: (data, response) => console.info(data, response),
239239
onError: (err) => console.info(err),
240240
},
241241
);

README.zh-CN.md

+6-6
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ const [createRequest, { hasPending, cancel }] = useRequest((id: string) =>
105105
```tsx
106106
interface CreateRequest {
107107
// Promise function
108-
ready: () => Promise<[Payload<TRequest>, AxiosRestResponse]>;
108+
ready: () => Promise<[Payload<TRequest>, AxiosResponse]>;
109109
// Axios Canceler. clear current request.
110110
cancel: Canceler;
111111
}
@@ -138,7 +138,7 @@ const [createRequest, { hasPending, cancel }] = useRequest(
138138
method: "DELETE",
139139
}),
140140
{
141-
onCompleted: (data, other) => console.info(data, other),
141+
onCompleted: (data, response) => console.info(data, response),
142142
onError: (err) => console.info(err),
143143
},
144144
);
@@ -154,7 +154,7 @@ const [createRequest, { hasPending, cancel }] = useRequest(
154154
| options.cacheKey | string\| number \| function | 自定义生成 Cache key 函数 |
155155
| options.cacheFilter | function | 缓存筛选器,自定义过滤响应缓存,决定是否存储 |
156156
| options.filter | function | 请求筛选器,决定是否发起请求 |
157-
| options.defaultState | object | State 的初始化值. `{data, other, error, isLoading}` |
157+
| options.defaultState | object | State 的初始化值. `{data, response, error, isLoading}` |
158158
| options.onCompleted | function | 请求成功的回调函数 |
159159
| options.onError | function | 请求失败的回调函数 |
160160
| options.instance | `AxiosInstance` | 自定义当前项的 Axios 实例 |
@@ -180,8 +180,8 @@ const [reqState, fetch] = useResource((id: string) =>
180180
interface ReqState {
181181
// Result
182182
data?: Payload<TRequest>;
183-
// other axios response. Omit<AxiosResponse, "data">
184-
other?: AxiosRestResponse;
183+
// axios response
184+
response?: AxiosResponse;
185185
// normalized error
186186
error?: RequestError<Payload<TRequest>>;
187187
isLoading: boolean;
@@ -235,7 +235,7 @@ const [reqState] = useResource(
235235
}),
236236
[],
237237
{
238-
onCompleted: (data, other) => console.info(data, other),
238+
onCompleted: (data, response) => console.info(data, response),
239239
onError: (err) => console.info(err),
240240
},
241241
);

src/request.ts

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type {
66
} from "axios";
77
import axios from "axios";
88

9+
/** @deprecated No longer use. Use `AxiosResponse` instead */
910
export type AxiosRestResponse<D = any> = Omit<
1011
AxiosResponse<unknown, D>,
1112
"data"
@@ -24,7 +25,7 @@ export interface RequestFactory<TRequest extends Request> {
2425
(...args: Parameters<TRequest>): {
2526
cancel: Canceler;
2627
ready: () => Promise<
27-
[Payload<TRequest>, AxiosRestResponse<CData<TRequest>>]
28+
[Payload<TRequest>, AxiosResponse<unknown, CData<TRequest>>]
2829
>;
2930
};
3031
}
@@ -49,7 +50,7 @@ export interface RequestError<
4950
export type RequestCallbackFn<TRequest extends Request> = {
5051
onCompleted?: (
5152
data?: Payload<TRequest>,
52-
other?: AxiosRestResponse<CData<TRequest>>,
53+
response?: AxiosResponse<CData<TRequest>>,
5354
) => void;
5455
onError?: (err?: RequestError<Payload<TRequest>, CData<TRequest>>) => void;
5556
};

src/useRequest.ts

+3-7
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import type {
1414
Request,
1515
Payload,
1616
CData,
17-
AxiosRestResponse,
1817
} from "./request";
1918
import { createRequestError } from "./request";
2019
import { RequestContext } from "./requestContext";
@@ -76,10 +75,9 @@ export function useRequest<TRequest extends Request>(
7675
.then(
7776
(response: AxiosResponse<Payload<TRequest>, CData<TRequest>>) => {
7877
removeCancelToken(source.token);
79-
const { data, ...restResponse } = response;
8078

81-
onCompletedRef.current?.(data, restResponse);
82-
return [data, restResponse];
79+
onCompletedRef.current?.(response.data, response);
80+
return [response.data, response];
8381
},
8482
)
8583
.catch((err: AxiosError<Payload<TRequest>, CData<TRequest>>) => {
@@ -92,9 +90,7 @@ export function useRequest<TRequest extends Request>(
9290
onErrorRef.current?.(error);
9391

9492
throw error;
95-
}) as Promise<
96-
[Payload<TRequest>, AxiosRestResponse<CData<TRequest>>]
97-
>;
93+
}) as Promise<[Payload<TRequest>, AxiosResponse<CData<TRequest>>]>;
9894
};
9995

10096
return {

src/useResource.ts

+13-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { useEffect, useCallback, useContext, useReducer, useMemo } from "react";
2-
import type { Canceler } from "axios";
2+
import type { Canceler, AxiosResponse } from "axios";
33
import { useRequest } from "./useRequest";
44
import type {
55
Payload,
@@ -8,7 +8,6 @@ import type {
88
Request,
99
RequestDispatcher,
1010
RequestCallbackFn,
11-
AxiosRestResponse,
1211
Resource,
1312
} from "./request";
1413
import type {
@@ -25,9 +24,12 @@ const REQUEST_CLEAR_MESSAGE =
2524

2625
type RequestState<TRequest extends Request> = {
2726
data?: Payload<TRequest>;
28-
other?: AxiosRestResponse<CData<TRequest>>;
27+
response?: AxiosResponse<CData<TRequest>>;
2928
error?: RequestError<Payload<TRequest>, CData<TRequest>>;
3029
isLoading?: boolean;
30+
31+
/** @deprecated Use `response` instead */
32+
other?: AxiosResponse<CData<TRequest>>;
3133
};
3234

3335
export type UseResourceResult<TRequest extends Request> = [
@@ -60,19 +62,23 @@ function getDefaultStateLoading<T extends Request>(
6062
}
6163

6264
type Action<T, D = any> =
63-
| { type: "success"; data: T; other: AxiosRestResponse<D> }
65+
| { type: "success"; data: T; response: AxiosResponse<D> }
6466
| { type: "error"; error: RequestError<T, D> }
6567
| { type: "reset" | "start" };
6668

6769
function getNextState<TRequest extends Request>(
6870
state: RequestState<TRequest>,
6971
action: Action<Payload<TRequest>, CData<TRequest>>,
7072
): RequestState<TRequest> {
73+
const response = action.type === "success" ? action.response : state.response;
74+
7175
return {
7276
data: action.type === "success" ? action.data : state.data,
73-
other: action.type === "success" ? action.other : state.other,
77+
response,
7478
error: action.type === "error" ? action.error : undefined,
7579
isLoading: action.type === "start" ? true : false,
80+
// will be deleted
81+
other: response,
7682
};
7783
}
7884

@@ -148,9 +154,9 @@ export function useResource<TRequest extends Request>(
148154
void (async () => {
149155
try {
150156
getMountedState() && dispatch({ type: "start" });
151-
const [data, other] = await ready();
157+
const [data, response] = await ready();
152158
if (getMountedState()) {
153-
dispatch({ type: "success", data, other });
159+
dispatch({ type: "success", data, response });
154160

155161
cacheKey &&
156162
requestCache &&

tests/useRequest.test.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,12 @@ describe("useRequest", () => {
3737
);
3838

3939
await act(async () => {
40-
const [data, other] = await result.current[0]().ready();
40+
const [data, res] = await result.current[0]().ready();
4141
expect(data).toStrictEqual(okResponse);
42-
expect(other?.status).toBe(200);
42+
expect(res.data).toStrictEqual(okResponse);
43+
expect(res?.status).toBe(200);
4344
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
44-
expect(other?.request?.responseURL).toBe("/users");
45+
expect(res?.request?.responseURL).toBe("/users");
4546
});
4647
});
4748

@@ -177,11 +178,11 @@ describe("useRequest", () => {
177178
expect(onCompleted).toHaveBeenCalledTimes(0);
178179
expect(onError).toHaveBeenCalledTimes(0);
179180

180-
const [data, other] = await result.current[0]().ready();
181+
const [data, res] = await result.current[0]().ready();
181182
expect(data).toStrictEqual(okResponse);
182183

183184
expect(onCompleted).toHaveBeenCalledTimes(1);
184-
expect(onCompleted).toHaveBeenCalledWith(data, other);
185+
expect(onCompleted).toHaveBeenCalledWith(data, res);
185186
expect(onError).toHaveBeenCalledTimes(0);
186187
});
187188
});

tests/useResource.test.tsx

+9
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ describe("useResource", () => {
4242

4343
expect(result.current[0].isLoading).toBeFalsy();
4444
expect(result.current[0].data).toBeUndefined();
45+
expect(result.current[0].response).toBeUndefined();
4546
expect(result.current[0].other).toBeUndefined();
4647

4748
void act(() => {
@@ -50,11 +51,14 @@ describe("useResource", () => {
5051

5152
expect(result.current[0].isLoading).toBeTruthy();
5253
expect(result.current[0].data).toBeUndefined();
54+
expect(result.current[0].response).toBeUndefined();
5355
expect(result.current[0].other).toBeUndefined();
5456

5557
await waitFor(() => {
5658
expect(result.current[0].error).toBeUndefined();
5759
expect(result.current[0].data).toStrictEqual(okResponse);
60+
expect(result.current[0].response?.data).toStrictEqual(okResponse);
61+
expect(result.current[0].response?.status).toBe(200);
5862
expect(result.current[0].other?.status).toBe(200);
5963
});
6064
});
@@ -389,6 +393,7 @@ describe("useResource", () => {
389393

390394
await waitForNextUpdate();
391395
expect(result.current[0].data).toBeUndefined();
396+
expect(result.current[0].response).toBeUndefined();
392397
expect(result.current[0].other).toBeUndefined();
393398
expect(result.current[0].error?.code).toBe(errResponse.code);
394399
expect(result.current[0].error?.data).toStrictEqual(errResponse);
@@ -781,6 +786,7 @@ describe("useResource - custom instance", () => {
781786

782787
expect(result.current[0].isLoading).toBeFalsy();
783788
expect(result.current[0].data).toBeUndefined();
789+
expect(result.current[0].response).toBeUndefined();
784790
expect(result.current[0].other).toBeUndefined();
785791

786792
void act(() => {
@@ -789,11 +795,14 @@ describe("useResource - custom instance", () => {
789795

790796
expect(result.current[0].isLoading).toBeTruthy();
791797
expect(result.current[0].data).toBeUndefined();
798+
expect(result.current[0].response).toBeUndefined();
792799
expect(result.current[0].other).toBeUndefined();
793800

794801
await waitFor(() => {
795802
expect(result.current[0].error).toBeUndefined();
796803
expect(result.current[0].data).toStrictEqual(okResponse2);
804+
expect(result.current[0].response?.data).toStrictEqual(okResponse2);
805+
expect(result.current[0].response?.status).toBe(200);
797806
expect(result.current[0].other?.status).toBe(200);
798807
});
799808
});

0 commit comments

Comments
 (0)