async-fetch 0.3.8 → 0.4.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 +84 -46
- package/dist/cjs/index.js +145 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/interfaces.js +3 -0
- package/dist/cjs/interfaces.js.map +1 -0
- package/dist/cjs/normalizeError.js +36 -0
- package/dist/cjs/normalizeError.js.map +1 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/types/index.d.ts +35 -0
- package/dist/cjs/types/index.d.ts.map +1 -0
- package/dist/{interfaces.d.ts → cjs/types/interfaces.d.ts} +4 -3
- package/dist/cjs/types/interfaces.d.ts.map +1 -0
- package/dist/cjs/types/normalizeError.d.ts +14 -0
- package/dist/cjs/types/normalizeError.d.ts.map +1 -0
- package/dist/cjs/types/useInterval.d.ts +12 -0
- package/dist/cjs/types/useInterval.d.ts.map +1 -0
- package/dist/cjs/useInterval.js +26 -0
- package/dist/cjs/useInterval.js.map +1 -0
- package/dist/{index.js → esm/index.js} +49 -19
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/interfaces.js +2 -0
- package/dist/esm/interfaces.js.map +1 -0
- package/dist/esm/normalizeError.js +34 -0
- package/dist/esm/normalizeError.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/types/index.d.ts +35 -0
- package/dist/esm/types/index.d.ts.map +1 -0
- package/dist/esm/types/interfaces.d.ts +31 -0
- package/dist/esm/types/interfaces.d.ts.map +1 -0
- package/dist/esm/types/normalizeError.d.ts +14 -0
- package/dist/esm/types/normalizeError.d.ts.map +1 -0
- package/dist/esm/types/useInterval.d.ts +12 -0
- package/dist/esm/types/useInterval.d.ts.map +1 -0
- package/dist/esm/useInterval.js +24 -0
- package/dist/esm/useInterval.js.map +1 -0
- package/package.json +59 -24
- package/dist/index.d.ts +0 -3
- package/dist/interfaces.js +0 -1
- package/dist/normalizeError.d.ts +0 -3
- package/dist/normalizeError.js +0 -22
- package/dist/useInterval.d.ts +0 -2
- package/dist/useInterval.js +0 -17
- package/tsconfig.json +0 -112
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nameer
|
|
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
CHANGED
|
@@ -1,19 +1,18 @@
|
|
|
1
|
-
#
|
|
1
|
+
# async-fetch
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A React hook for async fetch requests with built-in state management, cancellation, and polling.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
|
-
```
|
|
8
|
-
npm
|
|
7
|
+
```bash
|
|
8
|
+
npm install async-fetch
|
|
9
|
+
# or
|
|
10
|
+
yarn add async-fetch
|
|
9
11
|
```
|
|
10
12
|
|
|
11
13
|
## Usage
|
|
12
14
|
|
|
13
|
-
Provide a url and handle the request.
|
|
14
|
-
|
|
15
15
|
```javascript
|
|
16
|
-
import React from "react";
|
|
17
16
|
import useAsyncFetch from "async-fetch";
|
|
18
17
|
|
|
19
18
|
function App() {
|
|
@@ -23,14 +22,10 @@ function App() {
|
|
|
23
22
|
|
|
24
23
|
return (
|
|
25
24
|
<React.Fragment>
|
|
26
|
-
<button onClick={sendRequest}>Send request
|
|
27
|
-
<br />
|
|
28
|
-
<br />
|
|
25
|
+
<button onClick={sendRequest}>Send request</button>
|
|
29
26
|
<button onClick={cancelRequest} disabled={!pending}>
|
|
30
|
-
Cancel request
|
|
27
|
+
Cancel request
|
|
31
28
|
</button>
|
|
32
|
-
<br />
|
|
33
|
-
<br />
|
|
34
29
|
{pending
|
|
35
30
|
? "Loading..."
|
|
36
31
|
: data
|
|
@@ -41,39 +36,82 @@ function App() {
|
|
|
41
36
|
</React.Fragment>
|
|
42
37
|
);
|
|
43
38
|
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Auto-fetch on mount
|
|
42
|
+
|
|
43
|
+
By default the hook fires on mount. Set `auto: false` to disable:
|
|
44
|
+
|
|
45
|
+
```javascript
|
|
46
|
+
const { pending, data, sendRequest } = useAsyncFetch(url, { auto: false });
|
|
47
|
+
```
|
|
44
48
|
|
|
45
|
-
|
|
49
|
+
### POST with JSON body
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
const { pending, data, error } = useAsyncFetch("/api/submit", {
|
|
53
|
+
method: "POST",
|
|
54
|
+
data: { name: "foo" },
|
|
55
|
+
});
|
|
46
56
|
```
|
|
47
57
|
|
|
48
|
-
###
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
|
77
|
-
|
|
|
78
|
-
|
|
|
79
|
-
|
|
|
58
|
+
### Polling
|
|
59
|
+
|
|
60
|
+
```javascript
|
|
61
|
+
const { data } = useAsyncFetch("/api/status", { poll: 5000 });
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Callbacks
|
|
65
|
+
|
|
66
|
+
```javascript
|
|
67
|
+
useAsyncFetch("/api/user/1", {
|
|
68
|
+
onStart: () => console.log("started"),
|
|
69
|
+
onSuccess: (data) => console.log(data),
|
|
70
|
+
onFail: (error) => console.error(error),
|
|
71
|
+
onFinish: () => console.log("finished"),
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Cancel on demand
|
|
76
|
+
|
|
77
|
+
```javascript
|
|
78
|
+
const { cancelRequest } = useAsyncFetch("/api/user/1");
|
|
79
|
+
<button onClick={cancelRequest}>Cancel</button>;
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Request options
|
|
83
|
+
|
|
84
|
+
The minimum requirement is a URL string as the first argument. The second argument accepts the following options — anything else is passed directly to the underlying `fetch` call.
|
|
85
|
+
|
|
86
|
+
| Option | Type | Default | Description |
|
|
87
|
+
| ---------------- | ----------------------------------------------------------- | -------- | ---------------------------------------------------- |
|
|
88
|
+
| `initialPending` | `boolean` | `false` | Initial state for `pending` |
|
|
89
|
+
| `initialError` | `E` | | Initial state for `error` |
|
|
90
|
+
| `initialData` | `T` | | Initial state for `data` |
|
|
91
|
+
| `auto` | `boolean` | `true` | Whether to auto-send the request on mount |
|
|
92
|
+
| `poll` | `number` | | Milliseconds between polling requests |
|
|
93
|
+
| `timeout` | `number` | `30000` | Milliseconds before the request is cancelled |
|
|
94
|
+
| `ignoreRequest` | `boolean` | | Skips sending the request when `true` |
|
|
95
|
+
| `ignoreCleanup` | `boolean` | | Skips cancelling the request on unmount when `true` |
|
|
96
|
+
| `query` | `object` | | Key-value pairs appended to the URL as search params |
|
|
97
|
+
| `params` | `object` | | Key-value pairs appended to the URL as search params |
|
|
98
|
+
| `data` | `unknown` | | Value to send as the request body |
|
|
99
|
+
| `parser` | `"json" \| "text" \| "blob" \| "formData" \| "arrayBuffer"` | `"json"` | Method used to parse the response |
|
|
100
|
+
| `onStart` | `() => void` | | Called when the request starts |
|
|
101
|
+
| `onSuccess` | `(data: T) => void` | | Called with the response data on success |
|
|
102
|
+
| `onFail` | `(error: E) => void` | | Called with the error on failure |
|
|
103
|
+
| `onFinish` | `() => void` | | Called when the request finishes |
|
|
104
|
+
|
|
105
|
+
## Response
|
|
106
|
+
|
|
107
|
+
| Property | Type | Description |
|
|
108
|
+
| --------------- | --------------------- | ----------------------------- |
|
|
109
|
+
| `pending` | `boolean` | Whether the request is active |
|
|
110
|
+
| `error` | `E` | The response error |
|
|
111
|
+
| `data` | `T` | The response data |
|
|
112
|
+
| `sendRequest` | `() => Promise<void>` | Sends the request manually |
|
|
113
|
+
| `cancelRequest` | `() => void` | Cancels the active request |
|
|
114
|
+
|
|
115
|
+
## License
|
|
116
|
+
|
|
117
|
+
MIT
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const react_1 = require("react");
|
|
7
|
+
const useInterval_js_1 = __importDefault(require("./useInterval.js"));
|
|
8
|
+
const normalizeError_js_1 = __importDefault(require("./normalizeError.js"));
|
|
9
|
+
/**
|
|
10
|
+
* A React hook for managing async fetch requests with built-in state, cancellation, and polling.
|
|
11
|
+
* @example
|
|
12
|
+
* // Auto-fetch on mount:
|
|
13
|
+
* const { pending, error, data } = useAsyncFetch<User>("/api/user/1");
|
|
14
|
+
*
|
|
15
|
+
* // Manual trigger:
|
|
16
|
+
* const { pending, error, data, sendRequest } = useAsyncFetch<User>("/api/user/1", { auto: false });
|
|
17
|
+
* <button onClick={sendRequest}>Fetch</button>
|
|
18
|
+
*
|
|
19
|
+
* // With polling:
|
|
20
|
+
* const { data } = useAsyncFetch<Status>("/api/status", { poll: 5000 });
|
|
21
|
+
*
|
|
22
|
+
* // POST with JSON body:
|
|
23
|
+
* const { pending, error, data } = useAsyncFetch<Response>("/api/submit", {
|
|
24
|
+
* method: "POST",
|
|
25
|
+
* data: { name: "foo" },
|
|
26
|
+
* });
|
|
27
|
+
*
|
|
28
|
+
* // With callbacks:
|
|
29
|
+
* useAsyncFetch<User>("/api/user/1", {
|
|
30
|
+
* onStart: () => console.log("started"),
|
|
31
|
+
* onSuccess: (data) => console.log(data),
|
|
32
|
+
* onFail: (error) => console.error(error),
|
|
33
|
+
* onFinish: () => console.log("finished"),
|
|
34
|
+
* });
|
|
35
|
+
*
|
|
36
|
+
* // Cancel on demand:
|
|
37
|
+
* const { cancelRequest } = useAsyncFetch<User>("/api/user/1");
|
|
38
|
+
* <button onClick={cancelRequest}>Cancel</button>
|
|
39
|
+
*/
|
|
40
|
+
function useAsyncFetch(urlString, props = {}) {
|
|
41
|
+
const { initialPending = false, initialError, initialData, auto = true, poll, timeout = 30000, ignoreRequest, ignoreCleanup, query, params, data: body, parser = "json", onStart, onSuccess, onFail, onFinish, ...fetchOptions } = props;
|
|
42
|
+
const [pending, setPending] = (0, react_1.useState)(initialPending);
|
|
43
|
+
const [error, setError] = (0, react_1.useState)(initialError);
|
|
44
|
+
const [data, setData] = (0, react_1.useState)(initialData);
|
|
45
|
+
const fetchOptionsRef = (0, react_1.useRef)(fetchOptions);
|
|
46
|
+
const controllerRef = (0, react_1.useRef)(null);
|
|
47
|
+
const requestIdRef = (0, react_1.useRef)(0);
|
|
48
|
+
fetchOptionsRef.current = fetchOptions;
|
|
49
|
+
const cancelRequest = (0, react_1.useCallback)(() => {
|
|
50
|
+
controllerRef.current?.abort();
|
|
51
|
+
controllerRef.current = null;
|
|
52
|
+
}, []);
|
|
53
|
+
const sendRequest = (0, react_1.useCallback)(async () => {
|
|
54
|
+
if (ignoreRequest === true)
|
|
55
|
+
return;
|
|
56
|
+
cancelRequest();
|
|
57
|
+
setPending(true);
|
|
58
|
+
setError(undefined);
|
|
59
|
+
if (onStart)
|
|
60
|
+
onStart();
|
|
61
|
+
const controller = new AbortController();
|
|
62
|
+
controllerRef.current = controller;
|
|
63
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
64
|
+
const requestId = ++requestIdRef.current;
|
|
65
|
+
try {
|
|
66
|
+
const url = new URL(urlString, window.location.origin);
|
|
67
|
+
if (query ?? params) {
|
|
68
|
+
url.search = new URLSearchParams({ ...query, ...params }).toString();
|
|
69
|
+
}
|
|
70
|
+
const headers = new Headers(fetchOptionsRef.current.headers);
|
|
71
|
+
let resolvedBody;
|
|
72
|
+
if (headers.get("content-type") === "application/x-www-form-urlencoded") {
|
|
73
|
+
resolvedBody = new URLSearchParams(body ?? {});
|
|
74
|
+
}
|
|
75
|
+
else if (body instanceof FormData || body instanceof Blob) {
|
|
76
|
+
resolvedBody = body;
|
|
77
|
+
}
|
|
78
|
+
else if (body !== undefined) {
|
|
79
|
+
resolvedBody = JSON.stringify(body);
|
|
80
|
+
}
|
|
81
|
+
const response = await fetch(url, {
|
|
82
|
+
...fetchOptionsRef.current,
|
|
83
|
+
headers,
|
|
84
|
+
body: resolvedBody ?? fetchOptionsRef.current.body,
|
|
85
|
+
signal: controller.signal,
|
|
86
|
+
});
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
throw Object.assign(new Error(response.statusText), {
|
|
89
|
+
status: response.status,
|
|
90
|
+
statusText: response.statusText,
|
|
91
|
+
response: await response.text(),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const parsedResponse = (await response[parser]());
|
|
95
|
+
setData(parsedResponse);
|
|
96
|
+
if (onSuccess)
|
|
97
|
+
onSuccess(parsedResponse);
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
if (err?.name !== "AbortError") {
|
|
101
|
+
const normalizedError = (0, normalizeError_js_1.default)(err);
|
|
102
|
+
setError(normalizedError);
|
|
103
|
+
if (onFail)
|
|
104
|
+
onFail(normalizedError);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
finally {
|
|
108
|
+
clearTimeout(timeoutId);
|
|
109
|
+
if (requestId === requestIdRef.current) {
|
|
110
|
+
setPending(false);
|
|
111
|
+
if (onFinish)
|
|
112
|
+
onFinish();
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}, [
|
|
116
|
+
ignoreRequest,
|
|
117
|
+
cancelRequest,
|
|
118
|
+
timeout,
|
|
119
|
+
urlString,
|
|
120
|
+
query,
|
|
121
|
+
params,
|
|
122
|
+
body,
|
|
123
|
+
parser,
|
|
124
|
+
onStart,
|
|
125
|
+
onSuccess,
|
|
126
|
+
onFail,
|
|
127
|
+
onFinish,
|
|
128
|
+
]);
|
|
129
|
+
(0, react_1.useEffect)(() => {
|
|
130
|
+
if (auto === true)
|
|
131
|
+
void sendRequest();
|
|
132
|
+
}, [auto, sendRequest]);
|
|
133
|
+
(0, useInterval_js_1.default)(() => {
|
|
134
|
+
void sendRequest();
|
|
135
|
+
}, poll);
|
|
136
|
+
(0, react_1.useEffect)(() => {
|
|
137
|
+
return () => {
|
|
138
|
+
if (ignoreCleanup !== true)
|
|
139
|
+
cancelRequest();
|
|
140
|
+
};
|
|
141
|
+
}, [ignoreCleanup, cancelRequest]);
|
|
142
|
+
return { pending, error, data, cancelRequest, sendRequest };
|
|
143
|
+
}
|
|
144
|
+
exports.default = useAsyncFetch;
|
|
145
|
+
//# sourceMappingURL=index.js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E;QACD,aAAa;QACb,aAAa;QACb,OAAO;QACP,SAAS;QACT,KAAK;QACL,MAAM;QACN,IAAI;QACJ,MAAM;QACN,OAAO;QACP,SAAS;QACT,MAAM;QACN,QAAQ;KACT,CAAC,CAAC;IAEH,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,WAAW,EAAE,CAAC;IACxC,CAAC,EAAE,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC;IAExB,IAAA,wBAAW,EAAC,GAAG,EAAE;QACf,KAAK,WAAW,EAAE,CAAC;IACrB,CAAC,EAAE,IAAI,CAAC,CAAC;IAET,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,OAAO,GAAG,EAAE;YACV,IAAI,aAAa,KAAK,IAAI;gBAAE,aAAa,EAAE,CAAC;QAC9C,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,CAAC;IAEnC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC;AAC9D,CAAC;AAED,kBAAe,aAAa,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
/**
|
|
4
|
+
* Normalizes an unknown thrown value into a `FetchError`-shaped object.
|
|
5
|
+
* Handles `Error` instances, error-like objects, and primitive values.
|
|
6
|
+
* @example
|
|
7
|
+
* normalizeError(new Error("oops")) // { status: 500, statusText: "oops", response: "<stack>" }
|
|
8
|
+
* normalizeError({ status: 404, statusText: "Not Found", response: "" }) // { status: 404, statusText: "Not Found", response: "" }
|
|
9
|
+
* normalizeError({ status: 403 }) // { status: 403, statusText: "", response: "" }
|
|
10
|
+
* normalizeError("something went wrong") // { status: 500, statusText: "something went wrong", response: "" }
|
|
11
|
+
* normalizeError(null) // { status: 500, statusText: "null", response: "" }
|
|
12
|
+
*/
|
|
13
|
+
function normalizeError(err) {
|
|
14
|
+
if (err instanceof Error) {
|
|
15
|
+
return {
|
|
16
|
+
status: 500,
|
|
17
|
+
statusText: err.message,
|
|
18
|
+
response: err.stack ?? "",
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
if (typeof err === "object" && err !== null) {
|
|
22
|
+
const e = err;
|
|
23
|
+
return {
|
|
24
|
+
status: e.status ?? 500,
|
|
25
|
+
statusText: e.statusText ?? "",
|
|
26
|
+
response: e.response ?? "",
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
status: 500,
|
|
31
|
+
statusText: String(err),
|
|
32
|
+
response: "",
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
exports.default = normalizeError;
|
|
36
|
+
//# sourceMappingURL=normalizeError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalizeError.js","sourceRoot":"","sources":["../../src/normalizeError.ts"],"names":[],"mappings":";;AAEA;;;;;;;;;GASG;AACH,SAAS,cAAc,CAAiB,GAAY;IAClD,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;QACzB,OAAO;YACL,MAAM,EAAE,GAAG;YACX,UAAU,EAAE,GAAG,CAAC,OAAO;YACvB,QAAQ,EAAE,GAAG,CAAC,KAAK,IAAI,EAAE;SACrB,CAAC;IACT,CAAC;IAED,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QAC5C,MAAM,CAAC,GAAG,GAA0B,CAAC;QACrC,OAAO;YACL,MAAM,EAAE,CAAC,CAAC,MAAM,IAAI,GAAG;YACvB,UAAU,EAAE,CAAC,CAAC,UAAU,IAAI,EAAE;YAC9B,QAAQ,EAAE,CAAC,CAAC,QAAQ,IAAI,EAAE;SACtB,CAAC;IACT,CAAC;IAED,OAAO;QACL,MAAM,EAAE,GAAG;QACX,UAAU,EAAE,MAAM,CAAC,GAAG,CAAC;QACvB,QAAQ,EAAE,EAAE;KACR,CAAC;AACT,CAAC;AAED,kBAAe,cAAc,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type FetchError, type RequestProps, type ResponseProps } from "./interfaces.js";
|
|
2
|
+
/**
|
|
3
|
+
* A React hook for managing async fetch requests with built-in state, cancellation, and polling.
|
|
4
|
+
* @example
|
|
5
|
+
* // Auto-fetch on mount:
|
|
6
|
+
* const { pending, error, data } = useAsyncFetch<User>("/api/user/1");
|
|
7
|
+
*
|
|
8
|
+
* // Manual trigger:
|
|
9
|
+
* const { pending, error, data, sendRequest } = useAsyncFetch<User>("/api/user/1", { auto: false });
|
|
10
|
+
* <button onClick={sendRequest}>Fetch</button>
|
|
11
|
+
*
|
|
12
|
+
* // With polling:
|
|
13
|
+
* const { data } = useAsyncFetch<Status>("/api/status", { poll: 5000 });
|
|
14
|
+
*
|
|
15
|
+
* // POST with JSON body:
|
|
16
|
+
* const { pending, error, data } = useAsyncFetch<Response>("/api/submit", {
|
|
17
|
+
* method: "POST",
|
|
18
|
+
* data: { name: "foo" },
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* // With callbacks:
|
|
22
|
+
* useAsyncFetch<User>("/api/user/1", {
|
|
23
|
+
* onStart: () => console.log("started"),
|
|
24
|
+
* onSuccess: (data) => console.log(data),
|
|
25
|
+
* onFail: (error) => console.error(error),
|
|
26
|
+
* onFinish: () => console.log("finished"),
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* // Cancel on demand:
|
|
30
|
+
* const { cancelRequest } = useAsyncFetch<User>("/api/user/1");
|
|
31
|
+
* <button onClick={cancelRequest}>Cancel</button>
|
|
32
|
+
*/
|
|
33
|
+
declare function useAsyncFetch<T = unknown, E = FetchError>(urlString: string, props?: RequestProps<T, E>): ResponseProps<T, E>;
|
|
34
|
+
export default useAsyncFetch;
|
|
35
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,aAAa,EACnB,MAAM,iBAAiB,CAAC;AAKzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,iBAAS,aAAa,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,UAAU,EAChD,SAAS,EAAE,MAAM,EACjB,KAAK,GAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAM,GAC7B,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CA+IrB;AAED,eAAe,aAAa,CAAC"}
|
|
@@ -12,9 +12,9 @@ export interface RequestProps<T, E> extends RequestInit {
|
|
|
12
12
|
timeout?: number;
|
|
13
13
|
ignoreRequest?: boolean;
|
|
14
14
|
ignoreCleanup?: boolean;
|
|
15
|
-
query?: Record<string,
|
|
16
|
-
params?: Record<string,
|
|
17
|
-
data?:
|
|
15
|
+
query?: Record<string, string>;
|
|
16
|
+
params?: Record<string, string>;
|
|
17
|
+
data?: unknown;
|
|
18
18
|
parser?: "json" | "text" | "blob" | "formData" | "arrayBuffer";
|
|
19
19
|
onStart?: () => void;
|
|
20
20
|
onSuccess?: (data: T) => void;
|
|
@@ -28,3 +28,4 @@ export interface ResponseProps<T, E> {
|
|
|
28
28
|
sendRequest: () => Promise<void>;
|
|
29
29
|
cancelRequest: () => void;
|
|
30
30
|
}
|
|
31
|
+
//# sourceMappingURL=interfaces.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../src/interfaces.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,UA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izes an unknown thrown value into a `FetchError`-shaped object.
|
|
4
|
+
* Handles `Error` instances, error-like objects, and primitive values.
|
|
5
|
+
* @example
|
|
6
|
+
* normalizeError(new Error("oops")) // { status: 500, statusText: "oops", response: "<stack>" }
|
|
7
|
+
* normalizeError({ status: 404, statusText: "Not Found", response: "" }) // { status: 404, statusText: "Not Found", response: "" }
|
|
8
|
+
* normalizeError({ status: 403 }) // { status: 403, statusText: "", response: "" }
|
|
9
|
+
* normalizeError("something went wrong") // { status: 500, statusText: "something went wrong", response: "" }
|
|
10
|
+
* normalizeError(null) // { status: 500, statusText: "null", response: "" }
|
|
11
|
+
*/
|
|
12
|
+
declare function normalizeError<E = FetchError>(err: unknown): E;
|
|
13
|
+
export default normalizeError;
|
|
14
|
+
//# sourceMappingURL=normalizeError.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalizeError.d.ts","sourceRoot":"","sources":["../../../src/normalizeError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAElD;;;;;;;;;GASG;AACH,iBAAS,cAAc,CAAC,CAAC,GAAG,UAAU,EAAE,GAAG,EAAE,OAAO,GAAG,CAAC,CAuBvD;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sets up a polling interval that calls a callback on a given delay.
|
|
3
|
+
* The callback ref is kept up to date so stale closures are avoided.
|
|
4
|
+
* No interval is created if `poll` is not a valid integer.
|
|
5
|
+
* @see https://github.com/Hermanya/use-interval/blob/master/src/index.tsx
|
|
6
|
+
* @example
|
|
7
|
+
* useInterval(() => fetchData(), 5000) // calls fetchData every 5 seconds
|
|
8
|
+
* useInterval(() => fetchData()) // no interval created
|
|
9
|
+
*/
|
|
10
|
+
declare function useInterval(callback: () => void, poll?: number): void;
|
|
11
|
+
export default useInterval;
|
|
12
|
+
//# sourceMappingURL=useInterval.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useInterval.d.ts","sourceRoot":"","sources":["../../../src/useInterval.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,iBAAS,WAAW,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAc9D;AAED,eAAe,WAAW,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const react_1 = require("react");
|
|
4
|
+
/**
|
|
5
|
+
* Sets up a polling interval that calls a callback on a given delay.
|
|
6
|
+
* The callback ref is kept up to date so stale closures are avoided.
|
|
7
|
+
* No interval is created if `poll` is not a valid integer.
|
|
8
|
+
* @see https://github.com/Hermanya/use-interval/blob/master/src/index.tsx
|
|
9
|
+
* @example
|
|
10
|
+
* useInterval(() => fetchData(), 5000) // calls fetchData every 5 seconds
|
|
11
|
+
* useInterval(() => fetchData()) // no interval created
|
|
12
|
+
*/
|
|
13
|
+
function useInterval(callback, poll) {
|
|
14
|
+
const callbackRef = (0, react_1.useRef)(callback);
|
|
15
|
+
(0, react_1.useEffect)(() => {
|
|
16
|
+
callbackRef.current = callback;
|
|
17
|
+
}, [callback]);
|
|
18
|
+
(0, react_1.useEffect)(() => {
|
|
19
|
+
if (!Number.isInteger(poll))
|
|
20
|
+
return;
|
|
21
|
+
const id = setInterval(() => callbackRef.current(), poll);
|
|
22
|
+
return () => clearInterval(id);
|
|
23
|
+
}, [poll]);
|
|
24
|
+
}
|
|
25
|
+
exports.default = useInterval;
|
|
26
|
+
//# sourceMappingURL=useInterval.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useInterval.js","sourceRoot":"","sources":["../../src/useInterval.ts"],"names":[],"mappings":";;AAAA,iCAA0C;AAE1C;;;;;;;;GAQG;AACH,SAAS,WAAW,CAAC,QAAoB,EAAE,IAAa;IACtD,MAAM,WAAW,GAAG,IAAA,cAAM,EAAa,QAAQ,CAAC,CAAC;IAEjD,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,WAAW,CAAC,OAAO,GAAG,QAAQ,CAAC;IACjC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEf,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;YAAE,OAAO;QAEpC,MAAM,EAAE,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC;QAE1D,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACb,CAAC;AAED,kBAAe,WAAW,CAAC"}
|
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
import { useState, useRef, useCallback, useEffect } from "react";
|
|
2
2
|
import useInterval from "./useInterval.js";
|
|
3
3
|
import normalizeError from "./normalizeError.js";
|
|
4
|
+
/**
|
|
5
|
+
* A React hook for managing async fetch requests with built-in state, cancellation, and polling.
|
|
6
|
+
* @example
|
|
7
|
+
* // Auto-fetch on mount:
|
|
8
|
+
* const { pending, error, data } = useAsyncFetch<User>("/api/user/1");
|
|
9
|
+
*
|
|
10
|
+
* // Manual trigger:
|
|
11
|
+
* const { pending, error, data, sendRequest } = useAsyncFetch<User>("/api/user/1", { auto: false });
|
|
12
|
+
* <button onClick={sendRequest}>Fetch</button>
|
|
13
|
+
*
|
|
14
|
+
* // With polling:
|
|
15
|
+
* const { data } = useAsyncFetch<Status>("/api/status", { poll: 5000 });
|
|
16
|
+
*
|
|
17
|
+
* // POST with JSON body:
|
|
18
|
+
* const { pending, error, data } = useAsyncFetch<Response>("/api/submit", {
|
|
19
|
+
* method: "POST",
|
|
20
|
+
* data: { name: "foo" },
|
|
21
|
+
* });
|
|
22
|
+
*
|
|
23
|
+
* // With callbacks:
|
|
24
|
+
* useAsyncFetch<User>("/api/user/1", {
|
|
25
|
+
* onStart: () => console.log("started"),
|
|
26
|
+
* onSuccess: (data) => console.log(data),
|
|
27
|
+
* onFail: (error) => console.error(error),
|
|
28
|
+
* onFinish: () => console.log("finished"),
|
|
29
|
+
* });
|
|
30
|
+
*
|
|
31
|
+
* // Cancel on demand:
|
|
32
|
+
* const { cancelRequest } = useAsyncFetch<User>("/api/user/1");
|
|
33
|
+
* <button onClick={cancelRequest}>Cancel</button>
|
|
34
|
+
*/
|
|
4
35
|
function useAsyncFetch(urlString, props = {}) {
|
|
5
36
|
const { initialPending = false, initialError, initialData, auto = true, poll, timeout = 30000, ignoreRequest, ignoreCleanup, query, params, data: body, parser = "json", onStart, onSuccess, onFail, onFinish, ...fetchOptions } = props;
|
|
6
37
|
const [pending, setPending] = useState(initialPending);
|
|
@@ -28,7 +59,9 @@ function useAsyncFetch(urlString, props = {}) {
|
|
|
28
59
|
const requestId = ++requestIdRef.current;
|
|
29
60
|
try {
|
|
30
61
|
const url = new URL(urlString, window.location.origin);
|
|
31
|
-
|
|
62
|
+
if (query ?? params) {
|
|
63
|
+
url.search = new URLSearchParams({ ...query, ...params }).toString();
|
|
64
|
+
}
|
|
32
65
|
const headers = new Headers(fetchOptionsRef.current.headers);
|
|
33
66
|
let resolvedBody;
|
|
34
67
|
if (headers.get("content-type") === "application/x-www-form-urlencoded") {
|
|
@@ -47,22 +80,24 @@ function useAsyncFetch(urlString, props = {}) {
|
|
|
47
80
|
signal: controller.signal,
|
|
48
81
|
});
|
|
49
82
|
if (!response.ok) {
|
|
50
|
-
throw {
|
|
83
|
+
throw Object.assign(new Error(response.statusText), {
|
|
51
84
|
status: response.status,
|
|
52
85
|
statusText: response.statusText,
|
|
53
86
|
response: await response.text(),
|
|
54
|
-
};
|
|
87
|
+
});
|
|
55
88
|
}
|
|
56
89
|
const parsedResponse = (await response[parser]());
|
|
57
90
|
setData(parsedResponse);
|
|
58
|
-
onSuccess
|
|
91
|
+
if (onSuccess)
|
|
92
|
+
onSuccess(parsedResponse);
|
|
59
93
|
}
|
|
60
94
|
catch (err) {
|
|
61
|
-
if (err?.name
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
95
|
+
if (err?.name !== "AbortError") {
|
|
96
|
+
const normalizedError = normalizeError(err);
|
|
97
|
+
setError(normalizedError);
|
|
98
|
+
if (onFail)
|
|
99
|
+
onFail(normalizedError);
|
|
100
|
+
}
|
|
66
101
|
}
|
|
67
102
|
finally {
|
|
68
103
|
clearTimeout(timeoutId);
|
|
@@ -87,11 +122,11 @@ function useAsyncFetch(urlString, props = {}) {
|
|
|
87
122
|
onFinish,
|
|
88
123
|
]);
|
|
89
124
|
useEffect(() => {
|
|
90
|
-
if (auto)
|
|
91
|
-
sendRequest();
|
|
125
|
+
if (auto === true)
|
|
126
|
+
void sendRequest();
|
|
92
127
|
}, [auto, sendRequest]);
|
|
93
128
|
useInterval(() => {
|
|
94
|
-
sendRequest();
|
|
129
|
+
void sendRequest();
|
|
95
130
|
}, poll);
|
|
96
131
|
useEffect(() => {
|
|
97
132
|
return () => {
|
|
@@ -99,12 +134,7 @@ function useAsyncFetch(urlString, props = {}) {
|
|
|
99
134
|
cancelRequest();
|
|
100
135
|
};
|
|
101
136
|
}, [ignoreCleanup, cancelRequest]);
|
|
102
|
-
return {
|
|
103
|
-
pending,
|
|
104
|
-
error,
|
|
105
|
-
data,
|
|
106
|
-
cancelRequest,
|
|
107
|
-
sendRequest,
|
|
108
|
-
};
|
|
137
|
+
return { pending, error, data, cancelRequest, sendRequest };
|
|
109
138
|
}
|
|
110
139
|
export default useAsyncFetch;
|
|
140
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAA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AO;QACP,SAAS;QACT,MAAM;QACN,QAAQ;KACT,CAAC,CAAC;IAEH,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,IAAI,KAAK,IAAI;YAAE,KAAK,WAAW,EAAE,CAAC;IACxC,CAAC,EAAE,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC;IAExB,WAAW,CAAC,GAAG,EAAE;QACf,KAAK,WAAW,EAAE,CAAC;IACrB,CAAC,EAAE,IAAI,CAAC,CAAC;IAET,SAAS,CAAC,GAAG,EAAE;QACb,OAAO,GAAG,EAAE;YACV,IAAI,aAAa,KAAK,IAAI;gBAAE,aAAa,EAAE,CAAC;QAC9C,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,CAAC;IAEnC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,aAAa,EAAE,WAAW,EAAE,CAAC;AAC9D,CAAC;AAED,eAAe,aAAa,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../src/interfaces.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Normalizes an unknown thrown value into a `FetchError`-shaped object.
|
|
3
|
+
* Handles `Error` instances, error-like objects, and primitive values.
|
|
4
|
+
* @example
|
|
5
|
+
* normalizeError(new Error("oops")) // { status: 500, statusText: "oops", response: "<stack>" }
|
|
6
|
+
* normalizeError({ status: 404, statusText: "Not Found", response: "" }) // { status: 404, statusText: "Not Found", response: "" }
|
|
7
|
+
* normalizeError({ status: 403 }) // { status: 403, statusText: "", response: "" }
|
|
8
|
+
* normalizeError("something went wrong") // { status: 500, statusText: "something went wrong", response: "" }
|
|
9
|
+
* normalizeError(null) // { status: 500, statusText: "null", response: "" }
|
|
10
|
+
*/
|
|
11
|
+
function normalizeError(err) {
|
|
12
|
+
if (err instanceof Error) {
|
|
13
|
+
return {
|
|
14
|
+
status: 500,
|
|
15
|
+
statusText: err.message,
|
|
16
|
+
response: err.stack ?? "",
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
if (typeof err === "object" && err !== null) {
|
|
20
|
+
const e = err;
|
|
21
|
+
return {
|
|
22
|
+
status: e.status ?? 500,
|
|
23
|
+
statusText: e.statusText ?? "",
|
|
24
|
+
response: e.response ?? "",
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
status: 500,
|
|
29
|
+
statusText: String(err),
|
|
30
|
+
response: "",
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export default normalizeError;
|
|
34
|
+
//# sourceMappingURL=normalizeError.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalizeError.js","sourceRoot":"","sources":["../../src/normalizeError.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,SAAS,cAAc,CAAiB,GAAY;IAClD,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;QACzB,OAAO;YACL,MAAM,EAAE,GAAG;YACX,UAAU,EAAE,GAAG,CAAC,OAAO;YACvB,QAAQ,EAAE,GAAG,CAAC,KAAK,IAAI,EAAE;SACrB,CAAC;IACT,CAAC;IAED,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QAC5C,MAAM,CAAC,GAAG,GAA0B,CAAC;QACrC,OAAO;YACL,MAAM,EAAE,CAAC,CAAC,MAAM,IAAI,GAAG;YACvB,UAAU,EAAE,CAAC,CAAC,UAAU,IAAI,EAAE;YAC9B,QAAQ,EAAE,CAAC,CAAC,QAAQ,IAAI,EAAE;SACtB,CAAC;IACT,CAAC;IAED,OAAO;QACL,MAAM,EAAE,GAAG;QACX,UAAU,EAAE,MAAM,CAAC,GAAG,CAAC;QACvB,QAAQ,EAAE,EAAE;KACR,CAAC;AACT,CAAC;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type FetchError, type RequestProps, type ResponseProps } from "./interfaces.js";
|
|
2
|
+
/**
|
|
3
|
+
* A React hook for managing async fetch requests with built-in state, cancellation, and polling.
|
|
4
|
+
* @example
|
|
5
|
+
* // Auto-fetch on mount:
|
|
6
|
+
* const { pending, error, data } = useAsyncFetch<User>("/api/user/1");
|
|
7
|
+
*
|
|
8
|
+
* // Manual trigger:
|
|
9
|
+
* const { pending, error, data, sendRequest } = useAsyncFetch<User>("/api/user/1", { auto: false });
|
|
10
|
+
* <button onClick={sendRequest}>Fetch</button>
|
|
11
|
+
*
|
|
12
|
+
* // With polling:
|
|
13
|
+
* const { data } = useAsyncFetch<Status>("/api/status", { poll: 5000 });
|
|
14
|
+
*
|
|
15
|
+
* // POST with JSON body:
|
|
16
|
+
* const { pending, error, data } = useAsyncFetch<Response>("/api/submit", {
|
|
17
|
+
* method: "POST",
|
|
18
|
+
* data: { name: "foo" },
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* // With callbacks:
|
|
22
|
+
* useAsyncFetch<User>("/api/user/1", {
|
|
23
|
+
* onStart: () => console.log("started"),
|
|
24
|
+
* onSuccess: (data) => console.log(data),
|
|
25
|
+
* onFail: (error) => console.error(error),
|
|
26
|
+
* onFinish: () => console.log("finished"),
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* // Cancel on demand:
|
|
30
|
+
* const { cancelRequest } = useAsyncFetch<User>("/api/user/1");
|
|
31
|
+
* <button onClick={cancelRequest}>Cancel</button>
|
|
32
|
+
*/
|
|
33
|
+
declare function useAsyncFetch<T = unknown, E = FetchError>(urlString: string, props?: RequestProps<T, E>): ResponseProps<T, E>;
|
|
34
|
+
export default useAsyncFetch;
|
|
35
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,aAAa,EACnB,MAAM,iBAAiB,CAAC;AAKzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,iBAAS,aAAa,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,GAAG,UAAU,EAChD,SAAS,EAAE,MAAM,EACjB,KAAK,GAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAM,GAC7B,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CA+IrB;AAED,eAAe,aAAa,CAAC"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export interface FetchError {
|
|
2
|
+
status: number;
|
|
3
|
+
statusText: string;
|
|
4
|
+
response: string;
|
|
5
|
+
}
|
|
6
|
+
export interface RequestProps<T, E> extends RequestInit {
|
|
7
|
+
initialPending?: boolean;
|
|
8
|
+
initialError?: E;
|
|
9
|
+
initialData?: T;
|
|
10
|
+
auto?: boolean;
|
|
11
|
+
poll?: number;
|
|
12
|
+
timeout?: number;
|
|
13
|
+
ignoreRequest?: boolean;
|
|
14
|
+
ignoreCleanup?: boolean;
|
|
15
|
+
query?: Record<string, string>;
|
|
16
|
+
params?: Record<string, string>;
|
|
17
|
+
data?: unknown;
|
|
18
|
+
parser?: "json" | "text" | "blob" | "formData" | "arrayBuffer";
|
|
19
|
+
onStart?: () => void;
|
|
20
|
+
onSuccess?: (data: T) => void;
|
|
21
|
+
onFail?: (error: E) => void;
|
|
22
|
+
onFinish?: () => void;
|
|
23
|
+
}
|
|
24
|
+
export interface ResponseProps<T, E> {
|
|
25
|
+
pending: boolean;
|
|
26
|
+
error?: E;
|
|
27
|
+
data?: T;
|
|
28
|
+
sendRequest: () => Promise<void>;
|
|
29
|
+
cancelRequest: () => void;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=interfaces.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../../../src/interf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,0 +1,14 @@
|
|
|
1
|
+
import { type FetchError } from "./interfaces.js";
|
|
2
|
+
/**
|
|
3
|
+
* Normalizes an unknown thrown value into a `FetchError`-shaped object.
|
|
4
|
+
* Handles `Error` instances, error-like objects, and primitive values.
|
|
5
|
+
* @example
|
|
6
|
+
* normalizeError(new Error("oops")) // { status: 500, statusText: "oops", response: "<stack>" }
|
|
7
|
+
* normalizeError({ status: 404, statusText: "Not Found", response: "" }) // { status: 404, statusText: "Not Found", response: "" }
|
|
8
|
+
* normalizeError({ status: 403 }) // { status: 403, statusText: "", response: "" }
|
|
9
|
+
* normalizeError("something went wrong") // { status: 500, statusText: "something went wrong", response: "" }
|
|
10
|
+
* normalizeError(null) // { status: 500, statusText: "null", response: "" }
|
|
11
|
+
*/
|
|
12
|
+
declare function normalizeError<E = FetchError>(err: unknown): E;
|
|
13
|
+
export default normalizeError;
|
|
14
|
+
//# sourceMappingURL=normalizeError.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalizeError.d.ts","sourceRoot":"","sources":["../../../src/normalizeError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAElD;;;;;;;;;GASG;AACH,iBAAS,cAAc,CAAC,CAAC,GAAG,UAAU,EAAE,GAAG,EAAE,OAAO,GAAG,CAAC,CAuBvD;AAED,eAAe,cAAc,CAAC"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sets up a polling interval that calls a callback on a given delay.
|
|
3
|
+
* The callback ref is kept up to date so stale closures are avoided.
|
|
4
|
+
* No interval is created if `poll` is not a valid integer.
|
|
5
|
+
* @see https://github.com/Hermanya/use-interval/blob/master/src/index.tsx
|
|
6
|
+
* @example
|
|
7
|
+
* useInterval(() => fetchData(), 5000) // calls fetchData every 5 seconds
|
|
8
|
+
* useInterval(() => fetchData()) // no interval created
|
|
9
|
+
*/
|
|
10
|
+
declare function useInterval(callback: () => void, poll?: number): void;
|
|
11
|
+
export default useInterval;
|
|
12
|
+
//# sourceMappingURL=useInterval.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useInterval.d.ts","sourceRoot":"","sources":["../../../src/useInterval.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AACH,iBAAS,WAAW,CAAC,QAAQ,EAAE,MAAM,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAc9D;AAED,eAAe,WAAW,CAAC"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { useRef, useEffect } from "react";
|
|
2
|
+
/**
|
|
3
|
+
* Sets up a polling interval that calls a callback on a given delay.
|
|
4
|
+
* The callback ref is kept up to date so stale closures are avoided.
|
|
5
|
+
* No interval is created if `poll` is not a valid integer.
|
|
6
|
+
* @see https://github.com/Hermanya/use-interval/blob/master/src/index.tsx
|
|
7
|
+
* @example
|
|
8
|
+
* useInterval(() => fetchData(), 5000) // calls fetchData every 5 seconds
|
|
9
|
+
* useInterval(() => fetchData()) // no interval created
|
|
10
|
+
*/
|
|
11
|
+
function useInterval(callback, poll) {
|
|
12
|
+
const callbackRef = useRef(callback);
|
|
13
|
+
useEffect(() => {
|
|
14
|
+
callbackRef.current = callback;
|
|
15
|
+
}, [callback]);
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
if (!Number.isInteger(poll))
|
|
18
|
+
return;
|
|
19
|
+
const id = setInterval(() => callbackRef.current(), poll);
|
|
20
|
+
return () => clearInterval(id);
|
|
21
|
+
}, [poll]);
|
|
22
|
+
}
|
|
23
|
+
export default useInterval;
|
|
24
|
+
//# sourceMappingURL=useInterval.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useInterval.js","sourceRoot":"","sources":["../../src/useInterval.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAE1C;;;;;;;;GAQG;AACH,SAAS,WAAW,CAAC,QAAoB,EAAE,IAAa;IACtD,MAAM,WAAW,GAAG,MAAM,CAAa,QAAQ,CAAC,CAAC;IAEjD,SAAS,CAAC,GAAG,EAAE;QACb,WAAW,CAAC,OAAO,GAAG,QAAQ,CAAC;IACjC,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC;IAEf,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC;YAAE,OAAO;QAEpC,MAAM,EAAE,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,IAAI,CAAC,CAAC;QAE1D,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC;IACjC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;AACb,CAAC;AAED,eAAe,WAAW,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,35 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "async-fetch",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"scripts": {
|
|
9
|
-
"build": "npx rimraf dist && tsc",
|
|
10
|
-
"test-esm": "yarn build && node test/test-esm.mjs"
|
|
11
|
-
},
|
|
3
|
+
"packageManager": "yarn@4.13.0",
|
|
4
|
+
"version": "0.4.0",
|
|
5
|
+
"description": "A React hook for async fetch requests.",
|
|
6
|
+
"author": "Nameer Rizvi (https://github.com/nameer-rizvi)",
|
|
7
|
+
"license": "MIT",
|
|
12
8
|
"repository": {
|
|
13
9
|
"type": "git",
|
|
14
|
-
"url": "git+https://github.com/nameer-rizvi/
|
|
10
|
+
"url": "git+https://github.com/nameer-rizvi/async-fetch.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/nameer-rizvi/async-fetch#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/nameer-rizvi/async-fetch/issues"
|
|
15
15
|
},
|
|
16
16
|
"keywords": [
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"
|
|
17
|
+
"typescript",
|
|
18
|
+
"utils",
|
|
19
|
+
"utilities",
|
|
20
|
+
"esm",
|
|
21
|
+
"cjs"
|
|
21
22
|
],
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"main": "./dist/cjs/index.js",
|
|
28
|
+
"module": "./dist/esm/index.js",
|
|
29
|
+
"types": "./dist/cjs/types/index.d.ts",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"import": {
|
|
33
|
+
"types": "./dist/esm/types/index.d.ts",
|
|
34
|
+
"default": "./dist/esm/index.js"
|
|
35
|
+
},
|
|
36
|
+
"require": {
|
|
37
|
+
"types": "./dist/cjs/types/index.d.ts",
|
|
38
|
+
"default": "./dist/cjs/index.js"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"update": "yarn && node scripts/updateDeps.js",
|
|
47
|
+
"clean": "rimraf dist",
|
|
48
|
+
"lint": "eslint src/**/*",
|
|
49
|
+
"lint:fix": "eslint src/**/* --fix",
|
|
50
|
+
"build:cjs": "tsc -p tsconfig.cjs.json",
|
|
51
|
+
"build:esm": "tsc -p tsconfig.esm.json",
|
|
52
|
+
"build": "yarn clean && yarn lint && yarn build:cjs && yarn build:esm && node scripts/postbuild.mjs && echo '✅ Build complete! CJS and ESM outputs ready in dist/'",
|
|
53
|
+
"test:cjs": "node tests/test.cjs",
|
|
54
|
+
"test:esm": "node tests/test.mjs",
|
|
55
|
+
"test": "yarn build && yarn test:cjs && yarn test:esm",
|
|
56
|
+
"prepublishOnly": "yarn build"
|
|
26
57
|
},
|
|
27
|
-
"homepage": "https://github.com/nameer-rizvi/useAsyncFetch#readme",
|
|
28
58
|
"devDependencies": {
|
|
29
|
-
"@
|
|
30
|
-
"@types/react": "^19.2.
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"
|
|
59
|
+
"@eslint/js": "^10.0.1",
|
|
60
|
+
"@types/react": "^19.2.14",
|
|
61
|
+
"eslint": "^10.2.0",
|
|
62
|
+
"react": "^19.2.5",
|
|
63
|
+
"rimraf": "^6.1.3",
|
|
64
|
+
"typescript": "^6.0.2",
|
|
65
|
+
"typescript-eslint": "^8.58.0"
|
|
66
|
+
},
|
|
67
|
+
"peerDependencies": {
|
|
68
|
+
"react": ">=16"
|
|
34
69
|
}
|
|
35
70
|
}
|
package/dist/index.d.ts
DELETED
package/dist/interfaces.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/normalizeError.d.ts
DELETED
package/dist/normalizeError.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
function normalizeError(err) {
|
|
2
|
-
if (err instanceof Error) {
|
|
3
|
-
return {
|
|
4
|
-
status: 500,
|
|
5
|
-
statusText: err.message,
|
|
6
|
-
response: err.stack ?? "",
|
|
7
|
-
};
|
|
8
|
-
}
|
|
9
|
-
if (typeof err === "object" && err !== null) {
|
|
10
|
-
return {
|
|
11
|
-
status: err.status ?? 500,
|
|
12
|
-
statusText: err.statusText ?? "",
|
|
13
|
-
response: err.response ?? "",
|
|
14
|
-
};
|
|
15
|
-
}
|
|
16
|
-
return {
|
|
17
|
-
status: 500,
|
|
18
|
-
statusText: String(err),
|
|
19
|
-
response: "",
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
export default normalizeError;
|
package/dist/useInterval.d.ts
DELETED
package/dist/useInterval.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { useRef, useEffect } from "react";
|
|
2
|
-
function useInterval(callback, poll) {
|
|
3
|
-
const callbackRef = useRef(() => { });
|
|
4
|
-
useEffect(() => {
|
|
5
|
-
callbackRef.current = callback;
|
|
6
|
-
}, [callback]);
|
|
7
|
-
useEffect(() => {
|
|
8
|
-
if (!Number.isInteger(poll))
|
|
9
|
-
return;
|
|
10
|
-
const id = setInterval(() => {
|
|
11
|
-
callbackRef.current?.();
|
|
12
|
-
}, poll);
|
|
13
|
-
return () => clearInterval(id);
|
|
14
|
-
}, [poll]);
|
|
15
|
-
}
|
|
16
|
-
export default useInterval;
|
|
17
|
-
// https://github.com/Hermanya/use-interval/blob/master/src/index.tsx
|
package/tsconfig.json
DELETED
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
/* Visit https://aka.ms/tsconfig to read more about this file */
|
|
4
|
-
|
|
5
|
-
/* Projects */
|
|
6
|
-
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
|
7
|
-
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
|
8
|
-
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
|
9
|
-
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
|
10
|
-
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
|
11
|
-
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
|
12
|
-
|
|
13
|
-
/* Language and Environment */
|
|
14
|
-
"target": "ESNext" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
|
|
15
|
-
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
|
16
|
-
"jsx": "react-jsx" /* Specify what JSX code is generated. */,
|
|
17
|
-
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
|
18
|
-
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
|
19
|
-
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
|
20
|
-
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
21
|
-
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
22
|
-
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
23
|
-
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
24
|
-
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
25
|
-
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
26
|
-
|
|
27
|
-
/* Modules */
|
|
28
|
-
"module": "ESNext" /* Specify what module code is generated. */,
|
|
29
|
-
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
30
|
-
"moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */,
|
|
31
|
-
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
32
|
-
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
33
|
-
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
34
|
-
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
35
|
-
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
36
|
-
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
37
|
-
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
38
|
-
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
|
39
|
-
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
40
|
-
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
41
|
-
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
|
42
|
-
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
|
|
43
|
-
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
44
|
-
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
|
45
|
-
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
46
|
-
|
|
47
|
-
/* JavaScript Support */
|
|
48
|
-
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
49
|
-
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
50
|
-
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
51
|
-
|
|
52
|
-
/* Emit */
|
|
53
|
-
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
|
|
54
|
-
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
55
|
-
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
56
|
-
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
57
|
-
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
58
|
-
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
59
|
-
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
60
|
-
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
|
|
61
|
-
// "removeComments": true, /* Disable emitting comments. */
|
|
62
|
-
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
63
|
-
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
64
|
-
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
65
|
-
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
66
|
-
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
67
|
-
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
68
|
-
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
69
|
-
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
70
|
-
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
71
|
-
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
72
|
-
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
73
|
-
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
74
|
-
|
|
75
|
-
/* Interop Constraints */
|
|
76
|
-
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
77
|
-
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
|
78
|
-
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
|
|
79
|
-
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
80
|
-
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
|
|
81
|
-
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
82
|
-
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
|
|
83
|
-
|
|
84
|
-
/* Type Checking */
|
|
85
|
-
"strict": true /* Enable all strict type-checking options. */,
|
|
86
|
-
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
87
|
-
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
88
|
-
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
89
|
-
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
90
|
-
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
91
|
-
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
|
|
92
|
-
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
93
|
-
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
94
|
-
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
95
|
-
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
96
|
-
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
97
|
-
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
98
|
-
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
99
|
-
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
100
|
-
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
101
|
-
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
102
|
-
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
103
|
-
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
104
|
-
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
105
|
-
|
|
106
|
-
/* Completeness */
|
|
107
|
-
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
108
|
-
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
109
|
-
},
|
|
110
|
-
"include": ["src/**/*"], // Include all files in the src folder
|
|
111
|
-
"exclude": ["node_modules", "dist"] // Exclude node_modules and dist from the build
|
|
112
|
-
}
|