xansync 1.0.2 → 1.0.3
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/{index.mjs → index.cjs} +55 -51
- package/index.cjs.map +1 -0
- package/index.d.ts +9 -9
- package/index.js +51 -53
- package/index.js.map +1 -1
- package/package.json +21 -3
- package/readme.md +140 -137
- package/index.mjs.map +0 -1
package/{index.mjs → index.cjs}
RENAMED
|
@@ -1,55 +1,59 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
2
|
+
'use strict';
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const [
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
abortRef.current
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
4
|
+
var react = require('react');
|
|
5
|
+
|
|
6
|
+
function useSync(asyncFn, deps = []) {
|
|
7
|
+
const [data, setData] = react.useState(null);
|
|
8
|
+
const [isLoading, setLoading] = react.useState(true);
|
|
9
|
+
const [error, setError] = react.useState(null);
|
|
10
|
+
const abortRef = react.useRef(null);
|
|
11
|
+
const execute = react.useCallback(async () => {
|
|
12
|
+
var _a;
|
|
13
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
14
|
+
const controller = new AbortController();
|
|
15
|
+
abortRef.current = controller;
|
|
16
|
+
try {
|
|
17
|
+
setLoading(true);
|
|
18
|
+
setError(null);
|
|
19
|
+
const result = await asyncFn();
|
|
20
|
+
if (!controller.signal.aborted) {
|
|
21
|
+
setData(result);
|
|
22
|
+
setLoading(false);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
catch (err) {
|
|
26
|
+
if (!controller.signal.aborted) {
|
|
27
|
+
setError(err instanceof Error ? err : new Error("Unknown error"));
|
|
28
|
+
setLoading(false);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}, deps);
|
|
32
|
+
react.useEffect(() => {
|
|
33
|
+
execute();
|
|
34
|
+
return () => { var _a; return (_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
|
|
35
|
+
}, [execute]);
|
|
36
|
+
return {
|
|
37
|
+
data,
|
|
38
|
+
setData: (d) => setData(d),
|
|
39
|
+
isLoading,
|
|
40
|
+
error,
|
|
41
|
+
reload: execute
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
function withAsync(loader, render, fallback, onError) {
|
|
45
|
+
return function AsyncComponent() {
|
|
46
|
+
const { data, isLoading, error } = useSync(loader, []);
|
|
47
|
+
if (isLoading)
|
|
48
|
+
return fallback !== null && fallback !== void 0 ? fallback : null;
|
|
49
|
+
if (error)
|
|
50
|
+
return onError ? onError(error) : null;
|
|
51
|
+
if (data == null)
|
|
52
|
+
return null;
|
|
53
|
+
return render(data);
|
|
54
|
+
};
|
|
52
55
|
}
|
|
53
56
|
|
|
54
|
-
|
|
55
|
-
|
|
57
|
+
exports.useSync = useSync;
|
|
58
|
+
exports.withAsync = withAsync;
|
|
59
|
+
//# sourceMappingURL=index.cjs.map
|
package/index.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["\"use client\";\r\nimport { Dispatch, SetStateAction, useCallback, useEffect, useRef, useState } from \"react\";\r\n\r\nexport interface UseAsyncResult<T> {\r\n data: T | null;\r\n setData: Dispatch<SetStateAction<T | null>>\r\n isLoading: boolean;\r\n error: Error | null;\r\n reload: () => void;\r\n}\r\n\r\nexport function useSync<T>(asyncFn: () => Promise<T>, deps: any[] = []): UseAsyncResult<T> {\r\n const [data, setData] = useState<T | null>(null);\r\n const [isLoading, setLoading] = useState(true);\r\n const [error, setError] = useState<Error | null>(null);\r\n const abortRef = useRef<AbortController | null>(null);\r\n\r\n const execute = useCallback(async () => {\r\n\r\n abortRef.current?.abort();\r\n const controller = new AbortController();\r\n abortRef.current = controller;\r\n\r\n try {\r\n setLoading(true);\r\n setError(null);\r\n const result = await asyncFn();\r\n if (!controller.signal.aborted) {\r\n setData(result);\r\n setLoading(false);\r\n }\r\n } catch (err) {\r\n if (!controller.signal.aborted) {\r\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\r\n setLoading(false);\r\n }\r\n }\r\n }, deps);\r\n\r\n useEffect(() => {\r\n execute();\r\n return () => abortRef.current?.abort();\r\n }, [execute]);\r\n\r\n return {\r\n data,\r\n setData: (d) => setData(d),\r\n isLoading,\r\n error,\r\n reload: execute\r\n };\r\n}\r\n\r\ntype AsyncRenderer<T> = (data: T) => React.ReactNode;\r\n\r\nexport function withAsync<T>(\r\n loader: () => Promise<T>,\r\n render: AsyncRenderer<T>,\r\n fallback?: React.ReactNode,\r\n onError?: (error: Error) => React.ReactNode\r\n) {\r\n return function AsyncComponent() {\r\n const { data, isLoading, error } = useSync(loader, []);\r\n\r\n if (isLoading) return fallback ?? null;\r\n if (error) return onError ? onError(error) : null;\r\n if (data == null) return null;\r\n\r\n return render(data);\r\n };\r\n}\r\n"],"names":[],"mappings":";;;;;;;;;AAeE;AAEA;;AAEE;AACA;AACA;;;;AAKE;AACA;;;AAGC;AACF;AAAC;AACA;AACE;;AAED;AACF;;;AAID;AACA;AACF;;;;;;AAOE;;AAEJ;AAIM;AAMJ;AACE;AAEA;AAAe;AACf;AAAW;;AACO;AAElB;AACF;AACF;;;"}
|
package/index.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import * as react from 'react';
|
|
2
2
|
import { Dispatch, SetStateAction } from 'react';
|
|
3
3
|
|
|
4
|
-
interface UseAsyncResult<T> {
|
|
5
|
-
data: T | null;
|
|
6
|
-
setData: Dispatch<SetStateAction<T | null>>;
|
|
7
|
-
isLoading: boolean;
|
|
8
|
-
error: Error | null;
|
|
9
|
-
reload: () => void;
|
|
10
|
-
}
|
|
11
|
-
declare function useSync<T>(asyncFn: () => Promise<T>, deps?: any[]): UseAsyncResult<T>;
|
|
12
|
-
type AsyncRenderer<T> = (data: T) => React.ReactNode;
|
|
4
|
+
interface UseAsyncResult<T> {
|
|
5
|
+
data: T | null;
|
|
6
|
+
setData: Dispatch<SetStateAction<T | null>>;
|
|
7
|
+
isLoading: boolean;
|
|
8
|
+
error: Error | null;
|
|
9
|
+
reload: () => void;
|
|
10
|
+
}
|
|
11
|
+
declare function useSync<T>(asyncFn: () => Promise<T>, deps?: any[]): UseAsyncResult<T>;
|
|
12
|
+
type AsyncRenderer<T> = (data: T) => React.ReactNode;
|
|
13
13
|
declare function withAsync<T>(loader: () => Promise<T>, render: AsyncRenderer<T>, fallback?: React.ReactNode, onError?: (error: Error) => React.ReactNode): () => react.ReactNode;
|
|
14
14
|
|
|
15
15
|
export { useSync, withAsync };
|
package/index.js
CHANGED
|
@@ -1,58 +1,56 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
|
|
2
|
+
import { useState, useRef, useCallback, useEffect } from 'react';
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const [
|
|
8
|
-
const
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
function
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
};
|
|
4
|
+
function useSync(asyncFn, deps = []) {
|
|
5
|
+
const [data, setData] = useState(null);
|
|
6
|
+
const [isLoading, setLoading] = useState(true);
|
|
7
|
+
const [error, setError] = useState(null);
|
|
8
|
+
const abortRef = useRef(null);
|
|
9
|
+
const execute = useCallback(async () => {
|
|
10
|
+
var _a;
|
|
11
|
+
(_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort();
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
abortRef.current = controller;
|
|
14
|
+
try {
|
|
15
|
+
setLoading(true);
|
|
16
|
+
setError(null);
|
|
17
|
+
const result = await asyncFn();
|
|
18
|
+
if (!controller.signal.aborted) {
|
|
19
|
+
setData(result);
|
|
20
|
+
setLoading(false);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
catch (err) {
|
|
24
|
+
if (!controller.signal.aborted) {
|
|
25
|
+
setError(err instanceof Error ? err : new Error("Unknown error"));
|
|
26
|
+
setLoading(false);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}, deps);
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
execute();
|
|
32
|
+
return () => { var _a; return (_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
|
|
33
|
+
}, [execute]);
|
|
34
|
+
return {
|
|
35
|
+
data,
|
|
36
|
+
setData: (d) => setData(d),
|
|
37
|
+
isLoading,
|
|
38
|
+
error,
|
|
39
|
+
reload: execute
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function withAsync(loader, render, fallback, onError) {
|
|
43
|
+
return function AsyncComponent() {
|
|
44
|
+
const { data, isLoading, error } = useSync(loader, []);
|
|
45
|
+
if (isLoading)
|
|
46
|
+
return fallback !== null && fallback !== void 0 ? fallback : null;
|
|
47
|
+
if (error)
|
|
48
|
+
return onError ? onError(error) : null;
|
|
49
|
+
if (data == null)
|
|
50
|
+
return null;
|
|
51
|
+
return render(data);
|
|
52
|
+
};
|
|
54
53
|
}
|
|
55
54
|
|
|
56
|
-
|
|
57
|
-
exports.withAsync = withAsync;
|
|
55
|
+
export { useSync, withAsync };
|
|
58
56
|
//# sourceMappingURL=index.js.map
|
package/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["\"use client\";\nimport { Dispatch, SetStateAction, useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseAsyncResult<T> {\n data: T | null;\n setData: Dispatch<SetStateAction<T | null>>\n isLoading: boolean;\n error: Error | null;\n reload: () => void;\n}\n\nexport function useSync<T>(asyncFn: () => Promise<T>, deps: any[] = []): UseAsyncResult<T> {\n const [data, setData] = useState<T | null>(null);\n const [isLoading, setLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n\n const execute = useCallback(async () => {\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n setLoading(true);\n setError(null);\n const result = await asyncFn();\n if (!controller.signal.aborted) {\n setData(result);\n setLoading(false);\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\n }\n }\n }, deps);\n\n useEffect(() => {\n execute();\n return () => abortRef.current?.abort();\n }, [execute]);\n\n return {\n data,\n setData: (d) => setData(d),\n isLoading,\n error,\n reload: execute\n };\n}\n\ntype AsyncRenderer<T> = (data: T) => React.ReactNode;\n\nexport function withAsync<T>(\n loader: () => Promise<T>,\n render: AsyncRenderer<T>,\n fallback?: React.ReactNode,\n onError?: (error: Error) => React.ReactNode\n) {\n return function AsyncComponent() {\n const { data, isLoading, error } = useSync(loader, []);\n\n if (isLoading) return fallback ?? null;\n if (error) return onError ? onError(error) : null;\n if (data == null) return null;\n\n return render(data);\n };\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["\"use client\";\r\nimport { Dispatch, SetStateAction, useCallback, useEffect, useRef, useState } from \"react\";\r\n\r\nexport interface UseAsyncResult<T> {\r\n data: T | null;\r\n setData: Dispatch<SetStateAction<T | null>>\r\n isLoading: boolean;\r\n error: Error | null;\r\n reload: () => void;\r\n}\r\n\r\nexport function useSync<T>(asyncFn: () => Promise<T>, deps: any[] = []): UseAsyncResult<T> {\r\n const [data, setData] = useState<T | null>(null);\r\n const [isLoading, setLoading] = useState(true);\r\n const [error, setError] = useState<Error | null>(null);\r\n const abortRef = useRef<AbortController | null>(null);\r\n\r\n const execute = useCallback(async () => {\r\n\r\n abortRef.current?.abort();\r\n const controller = new AbortController();\r\n abortRef.current = controller;\r\n\r\n try {\r\n setLoading(true);\r\n setError(null);\r\n const result = await asyncFn();\r\n if (!controller.signal.aborted) {\r\n setData(result);\r\n setLoading(false);\r\n }\r\n } catch (err) {\r\n if (!controller.signal.aborted) {\r\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\r\n setLoading(false);\r\n }\r\n }\r\n }, deps);\r\n\r\n useEffect(() => {\r\n execute();\r\n return () => abortRef.current?.abort();\r\n }, [execute]);\r\n\r\n return {\r\n data,\r\n setData: (d) => setData(d),\r\n isLoading,\r\n error,\r\n reload: execute\r\n };\r\n}\r\n\r\ntype AsyncRenderer<T> = (data: T) => React.ReactNode;\r\n\r\nexport function withAsync<T>(\r\n loader: () => Promise<T>,\r\n render: AsyncRenderer<T>,\r\n fallback?: React.ReactNode,\r\n onError?: (error: Error) => React.ReactNode\r\n) {\r\n return function AsyncComponent() {\r\n const { data, isLoading, error } = useSync(loader, []);\r\n\r\n if (isLoading) return fallback ?? null;\r\n if (error) return onError ? onError(error) : null;\r\n if (data == null) return null;\r\n\r\n return render(data);\r\n };\r\n}\r\n"],"names":[],"mappings":";;;;;;;AAeE;AAEA;;AAEE;AACA;AACA;;;;AAKE;AACA;;;AAGC;AACF;AAAC;AACA;AACE;;AAED;AACF;;;AAID;AACA;AACF;;;;;;AAOE;;AAEJ;AAIM;AAMJ;AACE;AAEA;AAAe;AACf;AAAW;;AACO;AAElB;AACF;AACF;;"}
|
package/package.json
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "xansync",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"main": "./index.js",
|
|
5
5
|
"module": "./index.mjs",
|
|
6
6
|
"types": "./index.d.ts",
|
|
7
|
-
"
|
|
8
|
-
"
|
|
7
|
+
"homepage": "https://xansync.devnax.com",
|
|
8
|
+
"description": "Lightweight React utilities for managing asynchronous data, loading states, and errors.",
|
|
9
|
+
"keywords": [
|
|
10
|
+
"react",
|
|
11
|
+
"react-hooks",
|
|
12
|
+
"async",
|
|
13
|
+
"data-fetching",
|
|
14
|
+
"useSync",
|
|
15
|
+
"withAsync"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/devnax/xansync.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/devnax/xansync/issues"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"react": ">=16.8.0"
|
|
26
|
+
}
|
|
9
27
|
}
|
package/readme.md
CHANGED
|
@@ -1,137 +1,140 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
```
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
1
|
+
# xansync
|
|
2
|
+
|
|
3
|
+
Lightweight React utilities for loading asynchronous data in components. `xansync` provides a hook for managing data, loading and error state, plus a higher-order component for rendering a loaded value.
|
|
4
|
+
|
|
5
|
+
Website: [xansync.devnax.com](https://xansync.devnax.com)
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install xansync
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The package uses React hooks and should be used from a React component. In frameworks with server and client components, use it in a client component.
|
|
14
|
+
|
|
15
|
+
## `useSync`
|
|
16
|
+
|
|
17
|
+
Use `useSync` to run an asynchronous function and access its result and request state.
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import { useState } from "react";
|
|
21
|
+
import { useSync } from "xansync";
|
|
22
|
+
|
|
23
|
+
type Post = {
|
|
24
|
+
id: number;
|
|
25
|
+
title: string;
|
|
26
|
+
body: string;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function PostViewer() {
|
|
30
|
+
const [postId, setPostId] = useState(1);
|
|
31
|
+
const { data, isLoading, error, reload } = useSync<Post>(async () => {
|
|
32
|
+
const response = await fetch(
|
|
33
|
+
`https://jsonplaceholder.typicode.com/posts/${postId}`
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
if (!response.ok) {
|
|
37
|
+
throw new Error(`Request failed (${response.status})`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return response.json() as Promise<Post>;
|
|
41
|
+
}, [postId]);
|
|
42
|
+
|
|
43
|
+
if (error) {
|
|
44
|
+
return <p role="alert">Could not load post: {error.message}</p>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return (
|
|
48
|
+
<section>
|
|
49
|
+
{isLoading && <p>Loading...</p>}
|
|
50
|
+
{data && (
|
|
51
|
+
<article>
|
|
52
|
+
<h2>{data.title}</h2>
|
|
53
|
+
<p>{data.body}</p>
|
|
54
|
+
</article>
|
|
55
|
+
)}
|
|
56
|
+
<button onClick={() => setPostId((id) => id + 1)}>
|
|
57
|
+
Load next post
|
|
58
|
+
</button>
|
|
59
|
+
<button onClick={reload} disabled={isLoading}>
|
|
60
|
+
Reload
|
|
61
|
+
</button>
|
|
62
|
+
</section>
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Signature
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
useSync<T>(
|
|
71
|
+
asyncFn: () => Promise<T>,
|
|
72
|
+
deps: any[] = []
|
|
73
|
+
): UseAsyncResult<T>
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`deps` controls when the asynchronous function is recreated and run again. Include every changing value read by `asyncFn`; for example, include `postId` when the request uses it.
|
|
77
|
+
|
|
78
|
+
The returned `UseAsyncResult<T>` contains:
|
|
79
|
+
|
|
80
|
+
| Property | Type | Description |
|
|
81
|
+
| --- | --- | --- |
|
|
82
|
+
| `data` | `T \| null` | The most recently resolved value, or `null` before a value is available. |
|
|
83
|
+
| `setData` | `Dispatch<SetStateAction<T \| null>>` | Update the stored value directly. |
|
|
84
|
+
| `isLoading` | `boolean` | Whether the current operation is in progress. |
|
|
85
|
+
| `error` | `Error \| null` | The error from the most recent failed operation, if any. |
|
|
86
|
+
| `reload` | `() => void` | Run the asynchronous function again. |
|
|
87
|
+
|
|
88
|
+
When a new operation starts, the hook clears the previous error. If the component unmounts or a newer operation replaces the current one, the older result is ignored. The underlying promise is not cancelled; `asyncFn` does not receive an `AbortSignal`.
|
|
89
|
+
|
|
90
|
+
## `withAsync`
|
|
91
|
+
|
|
92
|
+
Use `withAsync` to create a component that loads a value and passes it to a render function.
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
import { withAsync } from "xansync";
|
|
96
|
+
|
|
97
|
+
type Profile = {
|
|
98
|
+
name: string;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const ProfileCard = withAsync<Profile>(
|
|
102
|
+
async () => {
|
|
103
|
+
const response = await fetch("/api/profile");
|
|
104
|
+
if (!response.ok) {
|
|
105
|
+
throw new Error(`Request failed (${response.status})`);
|
|
106
|
+
}
|
|
107
|
+
return response.json() as Promise<Profile>;
|
|
108
|
+
},
|
|
109
|
+
(profile) => <p>Welcome, {profile.name}.</p>,
|
|
110
|
+
<p>Loading profile...</p>,
|
|
111
|
+
(error) => <p role="alert">Could not load profile: {error.message}</p>
|
|
112
|
+
);
|
|
113
|
+
|
|
114
|
+
function App() {
|
|
115
|
+
return <ProfileCard />;
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Signature
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
withAsync<T>(
|
|
123
|
+
loader: () => Promise<T>,
|
|
124
|
+
render: (data: T) => React.ReactNode,
|
|
125
|
+
fallback?: React.ReactNode,
|
|
126
|
+
onError?: (error: Error) => React.ReactNode
|
|
127
|
+
): () => React.ReactNode
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The returned component invokes `loader` when it mounts, displays `fallback` while loading, and uses `onError` to render a failure state. If no fallback or error renderer is provided, it renders nothing for that state. It also renders nothing if the resolved value is `null` or `undefined`.
|
|
131
|
+
|
|
132
|
+
## Development
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
npm run start
|
|
136
|
+
npm run build
|
|
137
|
+
npm run release
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
These scripts run the corresponding `makepack` commands.
|
package/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["\"use client\";\nimport { Dispatch, SetStateAction, useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseAsyncResult<T> {\n data: T | null;\n setData: Dispatch<SetStateAction<T | null>>\n isLoading: boolean;\n error: Error | null;\n reload: () => void;\n}\n\nexport function useSync<T>(asyncFn: () => Promise<T>, deps: any[] = []): UseAsyncResult<T> {\n const [data, setData] = useState<T | null>(null);\n const [isLoading, setLoading] = useState(true);\n const [error, setError] = useState<Error | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n\n const execute = useCallback(async () => {\n\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n try {\n setLoading(true);\n setError(null);\n const result = await asyncFn();\n if (!controller.signal.aborted) {\n setData(result);\n setLoading(false);\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\n }\n }\n }, deps);\n\n useEffect(() => {\n execute();\n return () => abortRef.current?.abort();\n }, [execute]);\n\n return {\n data,\n setData: (d) => setData(d),\n isLoading,\n error,\n reload: execute\n };\n}\n\ntype AsyncRenderer<T> = (data: T) => React.ReactNode;\n\nexport function withAsync<T>(\n loader: () => Promise<T>,\n render: AsyncRenderer<T>,\n fallback?: React.ReactNode,\n onError?: (error: Error) => React.ReactNode\n) {\n return function AsyncComponent() {\n const { data, isLoading, error } = useSync(loader, []);\n\n if (isLoading) return fallback ?? null;\n if (error) return onError ? onError(error) : null;\n if (data == null) return null;\n\n return render(data);\n };\n}\n"],"names":[],"mappings":";;;;;;;AAeE;AAEA;;AAEE;AACA;AACA;;;;AAKE;AACA;;;AAGC;AACF;AAAC;AACA;AACE;AACD;AACF;;;AAID;AACA;AACF;;;;;;AAOE;;AAEJ;AAIM;AAMJ;AACE;AAEA;AAAe;AACf;AAAW;;AACO;AAElB;AACF;AACF;;"}
|