react-fetch-utils 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/Readme.md +326 -0
- package/dist/index.d.mts +45 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +127 -0
- package/dist/index.mjs +97 -0
- package/package.json +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Craig Wilson
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/Readme.md
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
# react-fetch-utils
|
|
2
|
+
|
|
3
|
+
Lightweight React hooks and utilities for fetch requests with cancellation support.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install react-fetch-utils
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Requirements
|
|
12
|
+
|
|
13
|
+
- React 16.8+
|
|
14
|
+
- Node 18+ (for package development/build tooling)
|
|
15
|
+
|
|
16
|
+
## Import
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import {
|
|
20
|
+
FetchPromise,
|
|
21
|
+
useQueries,
|
|
22
|
+
useRequest,
|
|
23
|
+
statusEnum,
|
|
24
|
+
type CancellablePromise,
|
|
25
|
+
type FetchPromiseParams,
|
|
26
|
+
type Status,
|
|
27
|
+
} from "react-fetch-utils";
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Exports
|
|
31
|
+
|
|
32
|
+
- `FetchPromise`
|
|
33
|
+
- `useQueries`
|
|
34
|
+
- `useRequest`
|
|
35
|
+
- `statusEnum`
|
|
36
|
+
- `CancellablePromise` (type)
|
|
37
|
+
- `FetchPromiseParams` (type)
|
|
38
|
+
- `Status` (type)
|
|
39
|
+
|
|
40
|
+
## Quick Start
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { useEffect } from "react";
|
|
44
|
+
import { FetchPromise, useRequest } from "react-fetch-utils";
|
|
45
|
+
|
|
46
|
+
type Todo = { id: number; title: string; completed: boolean };
|
|
47
|
+
|
|
48
|
+
function getTodo() {
|
|
49
|
+
return FetchPromise<Todo>({
|
|
50
|
+
url: "https://jsonplaceholder.typicode.com/todos/1",
|
|
51
|
+
method: "GET",
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function TodoCard() {
|
|
56
|
+
const { status, response } = useRequest(getTodo);
|
|
57
|
+
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
if (status !== 2 || !response) return;
|
|
60
|
+
console.log("Loaded:", response.title);
|
|
61
|
+
}, [status, response]);
|
|
62
|
+
|
|
63
|
+
if (status === 0) return <p>Idle</p>;
|
|
64
|
+
if (status === 1) return <p>Loading...</p>;
|
|
65
|
+
return <p>{response?.title}</p>;
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## API
|
|
70
|
+
|
|
71
|
+
### `FetchPromise`
|
|
72
|
+
|
|
73
|
+
Creates a cancellable promise around `fetch`.
|
|
74
|
+
|
|
75
|
+
Signature:
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
function FetchPromise<T = unknown>(
|
|
79
|
+
params: FetchPromiseParams,
|
|
80
|
+
): CancellablePromise<T>;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`FetchPromiseParams`:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
type FetchPromiseParams = {
|
|
87
|
+
url: string;
|
|
88
|
+
method: string;
|
|
89
|
+
body?: object | null;
|
|
90
|
+
respType?: "raw" | "json" | null;
|
|
91
|
+
};
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Behavior:
|
|
95
|
+
|
|
96
|
+
- Sends JSON body with `JSON.stringify(params.body)`.
|
|
97
|
+
- Sends headers:
|
|
98
|
+
- `Accept: application/json` (or `blob` when `respType: "raw"`)
|
|
99
|
+
- `Content-Type: application/json`
|
|
100
|
+
- Resolves with `response.json()` by default.
|
|
101
|
+
- Resolves with `response.blob()` when `respType: "raw"`.
|
|
102
|
+
- Rejects `401` with `{ reason: "Unauthorized", details: Response }`.
|
|
103
|
+
- Rejects all other failures as `{ reason: "Unknown", details: error }`.
|
|
104
|
+
- Returns a promise with `.cancel()` that aborts the underlying request.
|
|
105
|
+
|
|
106
|
+
Example (JSON):
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { FetchPromise } from "react-fetch-utils";
|
|
110
|
+
|
|
111
|
+
type User = { id: number; name: string };
|
|
112
|
+
|
|
113
|
+
export function getUser() {
|
|
114
|
+
return FetchPromise<User>({
|
|
115
|
+
url: "/api/user",
|
|
116
|
+
method: "POST",
|
|
117
|
+
body: { includeDetails: true },
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Example (raw `Blob` + cancellation):
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { FetchPromise } from "react-fetch-utils";
|
|
126
|
+
|
|
127
|
+
const download = FetchPromise<Blob>({
|
|
128
|
+
url: "/api/report",
|
|
129
|
+
method: "GET",
|
|
130
|
+
respType: "raw",
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
// Cancel if no longer needed
|
|
134
|
+
download.cancel();
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### `useQueries`
|
|
138
|
+
|
|
139
|
+
Tracks active cancellable promises and provides list management helpers.
|
|
140
|
+
|
|
141
|
+
Signature:
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
function useQueries(): {
|
|
145
|
+
list: CancellablePromise[];
|
|
146
|
+
cancelAll: () => void;
|
|
147
|
+
add: (query: CancellablePromise) => void;
|
|
148
|
+
remove: (query: CancellablePromise) => void;
|
|
149
|
+
};
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Example:
|
|
153
|
+
|
|
154
|
+
```tsx
|
|
155
|
+
import { useEffect } from "react";
|
|
156
|
+
import { FetchPromise, useQueries } from "react-fetch-utils";
|
|
157
|
+
|
|
158
|
+
export function SearchBox({ term }: { term: string }) {
|
|
159
|
+
const queries = useQueries();
|
|
160
|
+
|
|
161
|
+
useEffect(() => {
|
|
162
|
+
// Cancel older in-flight requests before starting a new one
|
|
163
|
+
queries.cancelAll();
|
|
164
|
+
|
|
165
|
+
const query = FetchPromise({
|
|
166
|
+
url: `/api/search?q=${encodeURIComponent(term)}`,
|
|
167
|
+
method: "GET",
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
queries.add(query);
|
|
171
|
+
|
|
172
|
+
query
|
|
173
|
+
.then(result => {
|
|
174
|
+
console.log(result);
|
|
175
|
+
})
|
|
176
|
+
.catch(error => {
|
|
177
|
+
// Abort rejections are surfaced in error.details
|
|
178
|
+
if (error?.details?.name === "AbortError") return;
|
|
179
|
+
console.error(error);
|
|
180
|
+
})
|
|
181
|
+
.finally(() => {
|
|
182
|
+
queries.remove(query);
|
|
183
|
+
});
|
|
184
|
+
}, [term]);
|
|
185
|
+
|
|
186
|
+
return <div>Active queries: {queries.list.length}</div>;
|
|
187
|
+
}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### `useRequest`
|
|
191
|
+
|
|
192
|
+
Runs a cancellable request factory on mount, tracks status, and caches by factory function name.
|
|
193
|
+
|
|
194
|
+
Signature:
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
function useRequest<T = unknown>(
|
|
198
|
+
fetchPromise: (() => CancellablePromise<T>) | null | undefined,
|
|
199
|
+
disableCache?: boolean,
|
|
200
|
+
): { status: Status; response: T | null };
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Behavior:
|
|
204
|
+
|
|
205
|
+
- Status transitions: `0` (idle) -> `1` (fetching) -> `2` (done)
|
|
206
|
+
- Uses `fetchPromise.name` as cache key.
|
|
207
|
+
- On cache hit and `disableCache === false`, returns cached data.
|
|
208
|
+
- On cache miss, cancels tracked queries, runs request, tracks/removes it, then stores response.
|
|
209
|
+
- Does not auto-run again on dependency changes; it executes once on mount for that hook instance.
|
|
210
|
+
|
|
211
|
+
Example (cached by default):
|
|
212
|
+
|
|
213
|
+
```tsx
|
|
214
|
+
import { useEffect } from "react";
|
|
215
|
+
import { FetchPromise, useRequest, statusEnum } from "react-fetch-utils";
|
|
216
|
+
|
|
217
|
+
type Profile = { name: string; role: string };
|
|
218
|
+
|
|
219
|
+
function loadProfile() {
|
|
220
|
+
return FetchPromise<Profile>({
|
|
221
|
+
url: "/api/profile",
|
|
222
|
+
method: "GET",
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function ProfilePanel() {
|
|
227
|
+
const { status, response } = useRequest(loadProfile);
|
|
228
|
+
|
|
229
|
+
useEffect(() => {
|
|
230
|
+
if (status !== 2 || !response) return;
|
|
231
|
+
console.log("Ready:", response.name);
|
|
232
|
+
}, [status, response]);
|
|
233
|
+
|
|
234
|
+
return <p>State: {statusEnum[status]}</p>;
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Example (disable cache):
|
|
239
|
+
|
|
240
|
+
```tsx
|
|
241
|
+
const { status, response } = useRequest(loadProfile, true);
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### `statusEnum`
|
|
245
|
+
|
|
246
|
+
Maps `Status` values to labels.
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
const statusEnum = {
|
|
250
|
+
0: "idle",
|
|
251
|
+
1: "fetching",
|
|
252
|
+
2: "done",
|
|
253
|
+
} as const;
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Example:
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import { statusEnum, type Status } from "react-fetch-utils";
|
|
260
|
+
|
|
261
|
+
function labelFor(status: Status) {
|
|
262
|
+
return statusEnum[status];
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
### `CancellablePromise` (type)
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
type CancellablePromise<T = unknown> = Promise<T> & {
|
|
270
|
+
cancel: () => void;
|
|
271
|
+
};
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
Example:
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
import { type CancellablePromise, FetchPromise } from "react-fetch-utils";
|
|
278
|
+
|
|
279
|
+
const req: CancellablePromise<{ ok: boolean }> = FetchPromise({
|
|
280
|
+
url: "/api/health",
|
|
281
|
+
method: "GET",
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
req.cancel();
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### `FetchPromiseParams` (type)
|
|
288
|
+
|
|
289
|
+
Example:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import { type FetchPromiseParams, FetchPromise } from "react-fetch-utils";
|
|
293
|
+
|
|
294
|
+
const request: FetchPromiseParams = {
|
|
295
|
+
url: "/api/items",
|
|
296
|
+
method: "POST",
|
|
297
|
+
body: { page: 1 },
|
|
298
|
+
respType: "json",
|
|
299
|
+
};
|
|
300
|
+
|
|
301
|
+
FetchPromise(request);
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
### `Status` (type)
|
|
305
|
+
|
|
306
|
+
```ts
|
|
307
|
+
type Status = 0 | 1 | 2;
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Example:
|
|
311
|
+
|
|
312
|
+
```ts
|
|
313
|
+
import { type Status, statusEnum } from "react-fetch-utils";
|
|
314
|
+
|
|
315
|
+
const status: Status = 1;
|
|
316
|
+
console.log(statusEnum[status]); // "fetching"
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## Notes
|
|
320
|
+
|
|
321
|
+
- `useRequest` is built on top of `useQueries`.
|
|
322
|
+
- For errors, attach `.catch(...)` where you create and consume `CancellablePromise` requests.
|
|
323
|
+
|
|
324
|
+
## License
|
|
325
|
+
|
|
326
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
interface FetchPromiseParams {
|
|
2
|
+
url: string;
|
|
3
|
+
method: string;
|
|
4
|
+
body?: object | null;
|
|
5
|
+
respType?: "raw" | "json" | null;
|
|
6
|
+
}
|
|
7
|
+
interface CancellablePromise<T = unknown> extends Promise<T> {
|
|
8
|
+
cancel: () => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* @param params - Request configuration
|
|
12
|
+
* @returns A promise with a `.cancel()` method that calls `AbortController.abort()`
|
|
13
|
+
*/
|
|
14
|
+
declare const FetchPromise: <T = unknown>(params: FetchPromiseParams) => CancellablePromise<T>;
|
|
15
|
+
|
|
16
|
+
declare function useQueries(): {
|
|
17
|
+
list: CancellablePromise<unknown>[];
|
|
18
|
+
cancelAll: () => void;
|
|
19
|
+
add: (query: CancellablePromise) => void;
|
|
20
|
+
remove: (query: CancellablePromise) => void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Status enumerator.
|
|
25
|
+
* 0 = "idle"
|
|
26
|
+
* 1 = "fetching"
|
|
27
|
+
* 2 = "done"
|
|
28
|
+
*/
|
|
29
|
+
declare const statusEnum: {
|
|
30
|
+
readonly 0: "idle";
|
|
31
|
+
readonly 1: "fetching";
|
|
32
|
+
readonly 2: "done";
|
|
33
|
+
};
|
|
34
|
+
type Status = 0 | 1 | 2;
|
|
35
|
+
/**
|
|
36
|
+
* @param fetchPromise - A factory function that returns a `CancellablePromise`
|
|
37
|
+
* @param disableCache - Disable cache and force a re-fetch every time this hook runs
|
|
38
|
+
* @returns `{ status, response }` where status is 0 (idle), 1 (fetching), or 2 (done)
|
|
39
|
+
*/
|
|
40
|
+
declare const useRequest: <T = unknown>(fetchPromise: (() => CancellablePromise<T>) | null | undefined, disableCache?: boolean) => {
|
|
41
|
+
status: Status;
|
|
42
|
+
response: T | null;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export { type CancellablePromise, FetchPromise, type FetchPromiseParams, type Status, statusEnum, useQueries, useRequest };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
interface FetchPromiseParams {
|
|
2
|
+
url: string;
|
|
3
|
+
method: string;
|
|
4
|
+
body?: object | null;
|
|
5
|
+
respType?: "raw" | "json" | null;
|
|
6
|
+
}
|
|
7
|
+
interface CancellablePromise<T = unknown> extends Promise<T> {
|
|
8
|
+
cancel: () => void;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* @param params - Request configuration
|
|
12
|
+
* @returns A promise with a `.cancel()` method that calls `AbortController.abort()`
|
|
13
|
+
*/
|
|
14
|
+
declare const FetchPromise: <T = unknown>(params: FetchPromiseParams) => CancellablePromise<T>;
|
|
15
|
+
|
|
16
|
+
declare function useQueries(): {
|
|
17
|
+
list: CancellablePromise<unknown>[];
|
|
18
|
+
cancelAll: () => void;
|
|
19
|
+
add: (query: CancellablePromise) => void;
|
|
20
|
+
remove: (query: CancellablePromise) => void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Status enumerator.
|
|
25
|
+
* 0 = "idle"
|
|
26
|
+
* 1 = "fetching"
|
|
27
|
+
* 2 = "done"
|
|
28
|
+
*/
|
|
29
|
+
declare const statusEnum: {
|
|
30
|
+
readonly 0: "idle";
|
|
31
|
+
readonly 1: "fetching";
|
|
32
|
+
readonly 2: "done";
|
|
33
|
+
};
|
|
34
|
+
type Status = 0 | 1 | 2;
|
|
35
|
+
/**
|
|
36
|
+
* @param fetchPromise - A factory function that returns a `CancellablePromise`
|
|
37
|
+
* @param disableCache - Disable cache and force a re-fetch every time this hook runs
|
|
38
|
+
* @returns `{ status, response }` where status is 0 (idle), 1 (fetching), or 2 (done)
|
|
39
|
+
*/
|
|
40
|
+
declare const useRequest: <T = unknown>(fetchPromise: (() => CancellablePromise<T>) | null | undefined, disableCache?: boolean) => {
|
|
41
|
+
status: Status;
|
|
42
|
+
response: T | null;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export { type CancellablePromise, FetchPromise, type FetchPromiseParams, type Status, statusEnum, useQueries, useRequest };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
FetchPromise: () => FetchPromise_default,
|
|
24
|
+
statusEnum: () => statusEnum,
|
|
25
|
+
useQueries: () => useQueries,
|
|
26
|
+
useRequest: () => useRequest
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
|
|
30
|
+
// src/FetchPromise.ts
|
|
31
|
+
var FetchPromise = (params) => {
|
|
32
|
+
const controller = new AbortController();
|
|
33
|
+
const signal = controller.signal;
|
|
34
|
+
const promise = new Promise(async function(resolve, reject) {
|
|
35
|
+
const headers = {
|
|
36
|
+
Accept: params.respType === "raw" ? "blob" : "application/json",
|
|
37
|
+
"Content-Type": "application/json"
|
|
38
|
+
};
|
|
39
|
+
await fetch(params.url, {
|
|
40
|
+
method: params.method,
|
|
41
|
+
signal,
|
|
42
|
+
headers,
|
|
43
|
+
body: JSON.stringify(params.body)
|
|
44
|
+
}).then((response) => {
|
|
45
|
+
if (response.status === 401) {
|
|
46
|
+
reject({ reason: "Unauthorized", details: response });
|
|
47
|
+
}
|
|
48
|
+
if (!response.ok) {
|
|
49
|
+
throw new Error(response.statusText);
|
|
50
|
+
}
|
|
51
|
+
if (params.respType === "raw") {
|
|
52
|
+
return response.blob();
|
|
53
|
+
}
|
|
54
|
+
return response.json();
|
|
55
|
+
}).then((data) => {
|
|
56
|
+
if (data !== void 0) resolve(data);
|
|
57
|
+
}).catch((error) => {
|
|
58
|
+
reject({ reason: "Unknown", details: error });
|
|
59
|
+
});
|
|
60
|
+
});
|
|
61
|
+
promise.cancel = () => controller.abort();
|
|
62
|
+
return promise;
|
|
63
|
+
};
|
|
64
|
+
var FetchPromise_default = FetchPromise;
|
|
65
|
+
|
|
66
|
+
// src/useQueries.ts
|
|
67
|
+
var import_react = require("react");
|
|
68
|
+
function useQueries() {
|
|
69
|
+
const [list, setList] = (0, import_react.useState)([]);
|
|
70
|
+
return {
|
|
71
|
+
list,
|
|
72
|
+
cancelAll: () => {
|
|
73
|
+
const tempList = [...list];
|
|
74
|
+
if (tempList.length > 0) {
|
|
75
|
+
tempList.forEach((q) => q.cancel());
|
|
76
|
+
setList([]);
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
add: (query) => {
|
|
80
|
+
setList((prev) => [...prev, query]);
|
|
81
|
+
},
|
|
82
|
+
remove: (query) => {
|
|
83
|
+
setList((prev) => prev.filter((q) => q !== query));
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// src/useRequest.ts
|
|
89
|
+
var import_react2 = require("react");
|
|
90
|
+
var statusEnum = {
|
|
91
|
+
0: "idle",
|
|
92
|
+
1: "fetching",
|
|
93
|
+
2: "done"
|
|
94
|
+
};
|
|
95
|
+
var useRequest = (fetchPromise, disableCache = false) => {
|
|
96
|
+
const cache = (0, import_react2.useRef)({});
|
|
97
|
+
const queries = useQueries();
|
|
98
|
+
const [status, setStatus] = (0, import_react2.useState)(0);
|
|
99
|
+
const [response, setResponse] = (0, import_react2.useState)(null);
|
|
100
|
+
(0, import_react2.useEffect)(() => {
|
|
101
|
+
if (!fetchPromise) return;
|
|
102
|
+
setStatus(1);
|
|
103
|
+
const cacheKey = fetchPromise.name;
|
|
104
|
+
if (cache.current[cacheKey] && !disableCache) {
|
|
105
|
+
setResponse(cache.current[cacheKey]);
|
|
106
|
+
setStatus(2);
|
|
107
|
+
} else {
|
|
108
|
+
queries.cancelAll();
|
|
109
|
+
const query = fetchPromise();
|
|
110
|
+
queries.add(query);
|
|
111
|
+
query.then((res) => {
|
|
112
|
+
queries.remove(query);
|
|
113
|
+
cache.current[cacheKey] = res;
|
|
114
|
+
setResponse(res);
|
|
115
|
+
setStatus(2);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
}, []);
|
|
119
|
+
return { status, response };
|
|
120
|
+
};
|
|
121
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
122
|
+
0 && (module.exports = {
|
|
123
|
+
FetchPromise,
|
|
124
|
+
statusEnum,
|
|
125
|
+
useQueries,
|
|
126
|
+
useRequest
|
|
127
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// src/FetchPromise.ts
|
|
2
|
+
var FetchPromise = (params) => {
|
|
3
|
+
const controller = new AbortController();
|
|
4
|
+
const signal = controller.signal;
|
|
5
|
+
const promise = new Promise(async function(resolve, reject) {
|
|
6
|
+
const headers = {
|
|
7
|
+
Accept: params.respType === "raw" ? "blob" : "application/json",
|
|
8
|
+
"Content-Type": "application/json"
|
|
9
|
+
};
|
|
10
|
+
await fetch(params.url, {
|
|
11
|
+
method: params.method,
|
|
12
|
+
signal,
|
|
13
|
+
headers,
|
|
14
|
+
body: JSON.stringify(params.body)
|
|
15
|
+
}).then((response) => {
|
|
16
|
+
if (response.status === 401) {
|
|
17
|
+
reject({ reason: "Unauthorized", details: response });
|
|
18
|
+
}
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
throw new Error(response.statusText);
|
|
21
|
+
}
|
|
22
|
+
if (params.respType === "raw") {
|
|
23
|
+
return response.blob();
|
|
24
|
+
}
|
|
25
|
+
return response.json();
|
|
26
|
+
}).then((data) => {
|
|
27
|
+
if (data !== void 0) resolve(data);
|
|
28
|
+
}).catch((error) => {
|
|
29
|
+
reject({ reason: "Unknown", details: error });
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
promise.cancel = () => controller.abort();
|
|
33
|
+
return promise;
|
|
34
|
+
};
|
|
35
|
+
var FetchPromise_default = FetchPromise;
|
|
36
|
+
|
|
37
|
+
// src/useQueries.ts
|
|
38
|
+
import { useState } from "react";
|
|
39
|
+
function useQueries() {
|
|
40
|
+
const [list, setList] = useState([]);
|
|
41
|
+
return {
|
|
42
|
+
list,
|
|
43
|
+
cancelAll: () => {
|
|
44
|
+
const tempList = [...list];
|
|
45
|
+
if (tempList.length > 0) {
|
|
46
|
+
tempList.forEach((q) => q.cancel());
|
|
47
|
+
setList([]);
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
add: (query) => {
|
|
51
|
+
setList((prev) => [...prev, query]);
|
|
52
|
+
},
|
|
53
|
+
remove: (query) => {
|
|
54
|
+
setList((prev) => prev.filter((q) => q !== query));
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/useRequest.ts
|
|
60
|
+
import { useState as useState2, useRef, useEffect } from "react";
|
|
61
|
+
var statusEnum = {
|
|
62
|
+
0: "idle",
|
|
63
|
+
1: "fetching",
|
|
64
|
+
2: "done"
|
|
65
|
+
};
|
|
66
|
+
var useRequest = (fetchPromise, disableCache = false) => {
|
|
67
|
+
const cache = useRef({});
|
|
68
|
+
const queries = useQueries();
|
|
69
|
+
const [status, setStatus] = useState2(0);
|
|
70
|
+
const [response, setResponse] = useState2(null);
|
|
71
|
+
useEffect(() => {
|
|
72
|
+
if (!fetchPromise) return;
|
|
73
|
+
setStatus(1);
|
|
74
|
+
const cacheKey = fetchPromise.name;
|
|
75
|
+
if (cache.current[cacheKey] && !disableCache) {
|
|
76
|
+
setResponse(cache.current[cacheKey]);
|
|
77
|
+
setStatus(2);
|
|
78
|
+
} else {
|
|
79
|
+
queries.cancelAll();
|
|
80
|
+
const query = fetchPromise();
|
|
81
|
+
queries.add(query);
|
|
82
|
+
query.then((res) => {
|
|
83
|
+
queries.remove(query);
|
|
84
|
+
cache.current[cacheKey] = res;
|
|
85
|
+
setResponse(res);
|
|
86
|
+
setStatus(2);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}, []);
|
|
90
|
+
return { status, response };
|
|
91
|
+
};
|
|
92
|
+
export {
|
|
93
|
+
FetchPromise_default as FetchPromise,
|
|
94
|
+
statusEnum,
|
|
95
|
+
useQueries,
|
|
96
|
+
useRequest
|
|
97
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "react-fetch-utils",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Lightweight React hooks and utilities for fetch requests with cancellation support",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
8
|
+
"dev": "tsup src/index.ts --format cjs,esm --dts --watch",
|
|
9
|
+
"test": "vitest run",
|
|
10
|
+
"test:watch": "vitest",
|
|
11
|
+
"typecheck": "tsc --noEmit",
|
|
12
|
+
"prepack": "npm run typecheck && npm run build",
|
|
13
|
+
"prepublishOnly": "npm run typecheck && npm run build"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/wilsocr88/react-fetch-utils.git"
|
|
18
|
+
},
|
|
19
|
+
"author": "Craig Wilson <wilsocr88@gmail.com>",
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"engines": {
|
|
25
|
+
"node": ">=18"
|
|
26
|
+
},
|
|
27
|
+
"bugs": {
|
|
28
|
+
"url": "https://github.com/wilsocr88/react-fetch-utils/issues"
|
|
29
|
+
},
|
|
30
|
+
"homepage": "https://github.com/wilsocr88/react-fetch-utils#readme",
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/react": "^19.2.17",
|
|
33
|
+
"jsdom": "^29.1.1",
|
|
34
|
+
"react": "^19.2.7",
|
|
35
|
+
"react-dom": "^19.2.7",
|
|
36
|
+
"tsup": "^8.5.1",
|
|
37
|
+
"typescript": "^6.0.3",
|
|
38
|
+
"vitest": "^3.2.4"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"react": ">=16.8.0"
|
|
42
|
+
},
|
|
43
|
+
"module": "./dist/index.mjs",
|
|
44
|
+
"types": "./dist/index.d.ts",
|
|
45
|
+
"exports": {
|
|
46
|
+
".": {
|
|
47
|
+
"types": "./dist/index.d.ts",
|
|
48
|
+
"import": "./dist/index.mjs",
|
|
49
|
+
"require": "./dist/index.js"
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist",
|
|
54
|
+
"README.md",
|
|
55
|
+
"LICENSE"
|
|
56
|
+
],
|
|
57
|
+
"sideEffects": false,
|
|
58
|
+
"keywords": [
|
|
59
|
+
"react",
|
|
60
|
+
"fetch",
|
|
61
|
+
"hooks",
|
|
62
|
+
"cancel",
|
|
63
|
+
"abort",
|
|
64
|
+
"request"
|
|
65
|
+
]
|
|
66
|
+
}
|