xansync 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/index.d.ts +14 -0
- package/index.js +56 -0
- package/index.js.map +1 -0
- package/index.mjs +53 -0
- package/index.mjs.map +1 -0
- package/package.json +9 -0
- package/readme.md +137 -0
package/index.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import * as react from 'react';
|
|
2
|
+
|
|
3
|
+
interface UseAsyncResult<T> {
|
|
4
|
+
data: T | null;
|
|
5
|
+
isLoading: boolean;
|
|
6
|
+
error: Error | null;
|
|
7
|
+
reload: () => void;
|
|
8
|
+
}
|
|
9
|
+
declare function useSync<T>(asyncFn: () => Promise<T>, deps?: any[]): UseAsyncResult<T>;
|
|
10
|
+
type AsyncRenderer<T> = (data: T) => React.ReactNode;
|
|
11
|
+
declare function withAsync<T>(loader: () => Promise<T>, render: AsyncRenderer<T>, fallback?: React.ReactNode, onError?: (error: Error) => React.ReactNode): () => react.ReactNode;
|
|
12
|
+
|
|
13
|
+
export { useSync, withAsync };
|
|
14
|
+
export type { UseAsyncResult };
|
package/index.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
var react = require('react');
|
|
5
|
+
|
|
6
|
+
function useSync(asyncFn, deps = []) {
|
|
7
|
+
const [data, setData] = react.useState(null);
|
|
8
|
+
const [isLoading, setLoading] = react.useState(false);
|
|
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
|
+
setLoading(true);
|
|
17
|
+
setError(null);
|
|
18
|
+
try {
|
|
19
|
+
const result = await asyncFn();
|
|
20
|
+
if (!controller.signal.aborted) {
|
|
21
|
+
setData(result);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch (err) {
|
|
25
|
+
if (!controller.signal.aborted) {
|
|
26
|
+
setError(err instanceof Error ? err : new Error("Unknown error"));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
if (!controller.signal.aborted) {
|
|
31
|
+
setLoading(false);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}, deps);
|
|
35
|
+
react.useEffect(() => {
|
|
36
|
+
execute();
|
|
37
|
+
return () => { var _a; return (_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
|
|
38
|
+
}, [execute]);
|
|
39
|
+
return { data, isLoading, error, reload: execute };
|
|
40
|
+
}
|
|
41
|
+
function withAsync(loader, render, fallback, onError) {
|
|
42
|
+
return function AsyncComponent() {
|
|
43
|
+
const { data, isLoading, error } = useSync(loader, []);
|
|
44
|
+
if (isLoading)
|
|
45
|
+
return fallback !== null && fallback !== void 0 ? fallback : null;
|
|
46
|
+
if (error)
|
|
47
|
+
return onError ? onError(error) : null;
|
|
48
|
+
if (data == null)
|
|
49
|
+
return null;
|
|
50
|
+
return render(data);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
exports.useSync = useSync;
|
|
55
|
+
exports.withAsync = withAsync;
|
|
56
|
+
//# sourceMappingURL=index.js.map
|
package/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseAsyncResult<T> {\n data: 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(false);\n const [error, setError] = useState<Error | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n\n const execute = useCallback(async () => {\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setLoading(true);\n setError(null);\n\n try {\n const result = await asyncFn();\n if (!controller.signal.aborted) {\n setData(result);\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\n }\n } finally {\n if (!controller.signal.aborted) {\n setLoading(false);\n }\n }\n }, deps);\n\n useEffect(() => {\n execute();\n return () => abortRef.current?.abort();\n }, [execute]);\n\n return { data, isLoading, error, reload: execute };\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":";;;;;;;;;AAcE;AAEA;;AACE;AACA;AACA;;;;AAME;AACA;;AAEC;AACF;AAAC;AACA;AACE;AACD;AACF;AAAS;AACR;;AAEC;AACF;;;AAID;AACA;AACF;;AAGF;AAIM;AAMJ;AACE;AAEA;AAAe;AACf;AAAW;;AACO;AAElB;AACF;AACF;;;"}
|
package/index.mjs
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useState, useRef, useCallback, useEffect } from 'react';
|
|
3
|
+
|
|
4
|
+
function useSync(asyncFn, deps = []) {
|
|
5
|
+
const [data, setData] = useState(null);
|
|
6
|
+
const [isLoading, setLoading] = useState(false);
|
|
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
|
+
setLoading(true);
|
|
15
|
+
setError(null);
|
|
16
|
+
try {
|
|
17
|
+
const result = await asyncFn();
|
|
18
|
+
if (!controller.signal.aborted) {
|
|
19
|
+
setData(result);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
if (!controller.signal.aborted) {
|
|
24
|
+
setError(err instanceof Error ? err : new Error("Unknown error"));
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
if (!controller.signal.aborted) {
|
|
29
|
+
setLoading(false);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}, deps);
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
execute();
|
|
35
|
+
return () => { var _a; return (_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
|
|
36
|
+
}, [execute]);
|
|
37
|
+
return { data, isLoading, error, reload: execute };
|
|
38
|
+
}
|
|
39
|
+
function withAsync(loader, render, fallback, onError) {
|
|
40
|
+
return function AsyncComponent() {
|
|
41
|
+
const { data, isLoading, error } = useSync(loader, []);
|
|
42
|
+
if (isLoading)
|
|
43
|
+
return fallback !== null && fallback !== void 0 ? fallback : null;
|
|
44
|
+
if (error)
|
|
45
|
+
return onError ? onError(error) : null;
|
|
46
|
+
if (data == null)
|
|
47
|
+
return null;
|
|
48
|
+
return render(data);
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export { useSync, withAsync };
|
|
53
|
+
//# sourceMappingURL=index.mjs.map
|
package/index.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nexport interface UseAsyncResult<T> {\n data: 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(false);\n const [error, setError] = useState<Error | null>(null);\n const abortRef = useRef<AbortController | null>(null);\n\n const execute = useCallback(async () => {\n abortRef.current?.abort();\n const controller = new AbortController();\n abortRef.current = controller;\n\n setLoading(true);\n setError(null);\n\n try {\n const result = await asyncFn();\n if (!controller.signal.aborted) {\n setData(result);\n }\n } catch (err) {\n if (!controller.signal.aborted) {\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\n }\n } finally {\n if (!controller.signal.aborted) {\n setLoading(false);\n }\n }\n }, deps);\n\n useEffect(() => {\n execute();\n return () => abortRef.current?.abort();\n }, [execute]);\n\n return { data, isLoading, error, reload: execute };\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":";;;;;;;AAcE;AAEA;;AACE;AACA;AACA;;;;AAME;AACA;;AAEC;AACF;AAAC;AACA;AACE;AACD;AACF;AAAS;AACR;;AAEC;AACF;;;AAID;AACA;AACF;;AAGF;AAIM;AAMJ;AACE;AAEA;AAAe;AACf;AAAW;;AACO;AAElB;AACF;AACF;;"}
|
package/package.json
ADDED
package/readme.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
Here's the updated documentation with the correct package name:
|
|
2
|
+
|
|
3
|
+
# `react-tsync` - React Hook and HOC for Handling Asynchronous Operations
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
`react-tsync` provides two utility functions for handling asynchronous operations in React: `useAsync` and `withAsync`. These hooks simplify the management of asynchronous data fetching, error handling, and reloading logic within React components.
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
- **`useAsync`**: A hook that handles asynchronous operations, loading states, and error handling within a component.
|
|
12
|
+
- **`withAsync`**: A higher-order component (HOC) that wraps a component to handle asynchronous operations with built-in loading and error fallback UI.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
To install the package, use npm or yarn:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install react-tsync
|
|
20
|
+
# or
|
|
21
|
+
yarn add react-tsync
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## API Documentation
|
|
25
|
+
|
|
26
|
+
### `useAsync`
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
const { data, isLoading, error, reload } = useAsync<T>(promise: Promise<T>, dependencies: any[] = []): UseAsyncResult<T>
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
#### Parameters
|
|
33
|
+
|
|
34
|
+
- **`promise`** (`Promise<T>`): A promise that represents an asynchronous operation. The hook will execute this promise and manage the loading and error states.
|
|
35
|
+
- **`dependencies`** (`any[]`, optional): An array of dependencies for the `useEffect` hook. It determines when the async operation should be re-triggered.
|
|
36
|
+
|
|
37
|
+
#### Returns
|
|
38
|
+
|
|
39
|
+
The `useAsync` hook returns an object with the following properties:
|
|
40
|
+
|
|
41
|
+
- **`data`** (`T | null`): The result of the asynchronous operation. If the operation hasn't completed yet, this will be `null`.
|
|
42
|
+
- **`isLoading`** (`boolean`): A flag indicating whether the asynchronous operation is in progress.
|
|
43
|
+
- **`error`** (`Error | null`): An error object if an error occurred during the operation. If no error occurred, this will be `null`.
|
|
44
|
+
- **`reload`** (`() => void`): A function to trigger a reload of the asynchronous operation. It toggles the reloading state, re-running the promise.
|
|
45
|
+
|
|
46
|
+
#### Example Usage
|
|
47
|
+
|
|
48
|
+
```tsx
|
|
49
|
+
const MyComponent = () => {
|
|
50
|
+
const { data, isLoading, error, reload } = useAsync(fetch(`https://jsonplaceholder.typicode.com/posts/${id}`), []);
|
|
51
|
+
|
|
52
|
+
if (isLoading) return <div>Loading...</div>;
|
|
53
|
+
if (error) return <div>Error: {error.message}</div>;
|
|
54
|
+
|
|
55
|
+
return (
|
|
56
|
+
<div>
|
|
57
|
+
<div>{data}</div>
|
|
58
|
+
<button onClick={reload}>Reload</button>
|
|
59
|
+
</div>
|
|
60
|
+
);
|
|
61
|
+
};
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### `withAsync`
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
const withAsync = (Component: ComponentPromise, fallback?: React.ReactNode, onError?: onError) => {
|
|
68
|
+
return function WrappedComponent<P>(props: P): React.ReactNode
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
#### Parameters
|
|
73
|
+
|
|
74
|
+
- **`Component`** (`ComponentPromise`): A function that returns a React component. This component will be wrapped by the HOC.
|
|
75
|
+
- **`fallback`** (`React.ReactNode`, optional): A React node to be shown while the data is loading.
|
|
76
|
+
- **`onError`** (`onError`, optional): A function that takes an error message and returns a React node. This will be displayed if an error occurs during the asynchronous operation.
|
|
77
|
+
|
|
78
|
+
#### Returns
|
|
79
|
+
|
|
80
|
+
- A React component that wraps the provided `Component` and handles asynchronous operations. This component will display the fallback UI while loading and handle errors using the provided `onError` function.
|
|
81
|
+
|
|
82
|
+
#### Example Usage
|
|
83
|
+
|
|
84
|
+
```tsx
|
|
85
|
+
const MyComponent = (props: { id: string }) => {
|
|
86
|
+
return <div>Data for {props.id}</div>;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const WrappedComponent = withAsync(MyComponent, <div>Loading...</div>, (error: string) => <div>Error: {error}</div>);
|
|
90
|
+
|
|
91
|
+
const App = () => {
|
|
92
|
+
return <WrappedComponent id="123" />;
|
|
93
|
+
};
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Example Usage
|
|
97
|
+
|
|
98
|
+
### Example 1: Using `useAsync` in a Component
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
const FetchDataComponent = () => {
|
|
102
|
+
const { data, isLoading, error, reload } = useAsync(fetch(`https://jsonplaceholder.typicode.com/posts/${id}`), []);
|
|
103
|
+
|
|
104
|
+
if (isLoading) return <div>Loading...</div>;
|
|
105
|
+
if (error) return <div>Error: {error.message}</div>;
|
|
106
|
+
|
|
107
|
+
return (
|
|
108
|
+
<div>
|
|
109
|
+
<div>{data.bod}</div>
|
|
110
|
+
<button onClick={reload}>Reload</button>
|
|
111
|
+
</div>
|
|
112
|
+
);
|
|
113
|
+
};
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### Example 2: Using `withAsync` to Wrap a Component
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
const MyComponent = async ({ id }: { id: string }) => {
|
|
120
|
+
const data = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`)
|
|
121
|
+
return <div>Data for {data.body}</div>;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const WrappedComponent = withAsync(MyComponent, <div>Loading...</div>, (error: string) => <div>Error: {error}</div>);
|
|
125
|
+
|
|
126
|
+
const App = () => {
|
|
127
|
+
return <WrappedComponent id="123" />;
|
|
128
|
+
};
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## License
|
|
132
|
+
|
|
133
|
+
This package is open-source and available under the MIT License.
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
You can now publish this documentation along with your package `react-tsync` on npm!
|