xansync 1.0.2 → 1.0.4

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.cjs ADDED
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ var useSync = require('./useSync.cjs');
4
+ var withSync = require('./withSync.cjs');
5
+
6
+
7
+
8
+ exports.useSync = useSync.useSync;
9
+ exports.withSync = withSync.withSync;
10
+ //# sourceMappingURL=index.cjs.map
package/index.cjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
package/index.d.ts CHANGED
@@ -1,16 +1,2 @@
1
- import * as react from 'react';
2
- import { Dispatch, SetStateAction } from 'react';
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;
13
- declare function withAsync<T>(loader: () => Promise<T>, render: AsyncRenderer<T>, fallback?: React.ReactNode, onError?: (error: Error) => React.ReactNode): () => react.ReactNode;
14
-
15
- export { useSync, withAsync };
16
- export type { UseAsyncResult };
1
+ export { useSync } from './useSync.js';
2
+ export { withSync } from './withSync.js';
package/index.js CHANGED
@@ -1,58 +1,3 @@
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(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
- }
29
- }
30
- }, deps);
31
- react.useEffect(() => {
32
- execute();
33
- return () => { var _a; return (_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
34
- }, [execute]);
35
- return {
36
- data,
37
- setData: (d) => setData(d),
38
- isLoading,
39
- error,
40
- reload: execute
41
- };
42
- }
43
- function withAsync(loader, render, fallback, onError) {
44
- return function AsyncComponent() {
45
- const { data, isLoading, error } = useSync(loader, []);
46
- if (isLoading)
47
- return fallback !== null && fallback !== void 0 ? fallback : null;
48
- if (error)
49
- return onError ? onError(error) : null;
50
- if (data == null)
51
- return null;
52
- return render(data);
53
- };
54
- }
55
-
56
- exports.useSync = useSync;
57
- exports.withAsync = withAsync;
1
+ export { useSync } from './useSync.js';
2
+ export { withSync } from './withSync.js';
58
3
  //# 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":";;;;;;;;;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;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
package/package.json CHANGED
@@ -1,9 +1,27 @@
1
1
  {
2
2
  "name": "xansync",
3
- "version": "1.0.2",
3
+ "version": "1.0.4",
4
4
  "main": "./index.js",
5
5
  "module": "./index.mjs",
6
6
  "types": "./index.d.ts",
7
- "description": "",
8
- "keywords": []
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,139 @@
1
- Here's the updated documentation with the correct package name:
2
-
3
- # `xansync` - React Hook and HOC for Handling Asynchronous Operations
4
-
5
- ## Overview
6
-
7
- `xansync` provides two utility functions for handling asynchronous operations in React: `useSync` and `withAsync`. These hooks simplify the management of asynchronous data fetching, error handling, and reloading logic within React components.
8
-
9
- ### Features
10
-
11
- - **`useSync`**: 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 xansync
20
- # or
21
- yarn add xansync
22
- ```
23
-
24
- ## API Documentation
25
-
26
- ### `useSync`
27
-
28
- ```ts
29
- const { data, isLoading, error, reload } = useSync<T>(promise: Promise<T>, dependencies: any[] = []): useSyncResult<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 `useSync` 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 } = useSync(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 `useSync` in a Component
99
-
100
- ```tsx
101
- const FetchDataComponent = () => {
102
- const { data, isLoading, error, reload } = useSync(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 `xansync` on npm!
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
+ ## `withSync`
91
+
92
+ Use `withSync` to wrap an asynchronous component function. It receives the component props, waits for its promise to resolve to a React node, and then renders that node.
93
+
94
+ ```tsx
95
+ import { withSync } from "xansync";
96
+
97
+ type Profile = {
98
+ name: string;
99
+ };
100
+
101
+ type ProfileProps = {
102
+ userId: string;
103
+ };
104
+
105
+ const ProfileCard = withSync<ProfileProps>(
106
+ async ({ userId }) => {
107
+ const response = await fetch(`/api/profile/${encodeURIComponent(userId)}`);
108
+ if (!response.ok) {
109
+ throw new Error(`Request failed (${response.status})`);
110
+ }
111
+ const profile = (await response.json()) as Profile;
112
+ return <p>Welcome, {profile.name}.</p>;
113
+ }
114
+ );
115
+
116
+ function App() {
117
+ return <ProfileCard userId="123" />;
118
+ }
119
+ ```
120
+
121
+ ### Signature
122
+
123
+ ```ts
124
+ withSync<P extends object>(
125
+ Component: (props: P) => Promise<React.ReactNode>
126
+ ): (props: P) => React.ReactNode
127
+ ```
128
+
129
+ The wrapped component starts the async function after mounting and runs it again when the props object changes. It renders nothing while loading. If the promise rejects, the error is thrown during rendering so the nearest React error boundary can handle it. When props change or the component unmounts, results from the previous request are ignored; the underlying promise is not cancelled.
130
+
131
+ ## Development
132
+
133
+ ```bash
134
+ npm run start
135
+ npm run build
136
+ npm run release
137
+ ```
138
+
139
+ These scripts run the corresponding `makepack` commands.
package/useSync.cjs ADDED
@@ -0,0 +1,46 @@
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(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
+
45
+ exports.useSync = useSync;
46
+ //# sourceMappingURL=useSync.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSync.cjs","sources":["../src/useSync.ts"],"sourcesContent":["\"use client\";\r\nimport {\r\n Dispatch,\r\n SetStateAction,\r\n useCallback,\r\n useEffect,\r\n useRef,\r\n useState,\r\n} 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>(\r\n asyncFn: () => Promise<T>,\r\n deps: any[] = [],\r\n): 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 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"],"names":[],"mappings":";;;;;;;;;AAyBE;AAEA;;AACE;AACA;AACA;;;;AAKE;AACA;;;AAGC;AACF;AAAC;AACA;AACE;;AAED;AACF;;;AAID;AACA;AACF;;;;;;AAOE;;AAEJ;;"}
package/useSync.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { Dispatch, SetStateAction } from 'react';
2
+
3
+ interface UseAsyncResult<T> {
4
+ data: T | null;
5
+ setData: Dispatch<SetStateAction<T | null>>;
6
+ isLoading: boolean;
7
+ error: Error | null;
8
+ reload: () => void;
9
+ }
10
+ declare function useSync<T>(asyncFn: () => Promise<T>, deps?: any[]): UseAsyncResult<T>;
11
+
12
+ export { useSync };
13
+ export type { UseAsyncResult };
@@ -1,55 +1,44 @@
1
1
  "use client";
2
2
  import { useState, useRef, useCallback, useEffect } from 'react';
3
3
 
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
- }
27
- }
28
- }, deps);
29
- useEffect(() => {
30
- execute();
31
- return () => { var _a; return (_a = abortRef.current) === null || _a === void 0 ? void 0 : _a.abort(); };
32
- }, [execute]);
33
- return {
34
- data,
35
- setData: (d) => setData(d),
36
- isLoading,
37
- error,
38
- reload: execute
39
- };
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
- };
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
+ };
52
41
  }
53
42
 
54
- export { useSync, withAsync };
55
- //# sourceMappingURL=index.mjs.map
43
+ export { useSync };
44
+ //# sourceMappingURL=useSync.js.map
package/useSync.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSync.js","sources":["../src/useSync.ts"],"sourcesContent":["\"use client\";\r\nimport {\r\n Dispatch,\r\n SetStateAction,\r\n useCallback,\r\n useEffect,\r\n useRef,\r\n useState,\r\n} 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>(\r\n asyncFn: () => Promise<T>,\r\n deps: any[] = [],\r\n): 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 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"],"names":[],"mappings":";;;;;;;AAyBE;AAEA;;AACE;AACA;AACA;;;;AAKE;AACA;;;AAGC;AACF;AAAC;AACA;AACE;;AAED;AACF;;;AAID;AACA;AACF;;;;;;AAOE;;AAEJ;;"}
package/withSync.cjs ADDED
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+
5
+ function withSync(Component) {
6
+ return function SyncComponent(props) {
7
+ const [content, setContent] = react.useState(null);
8
+ const [isLoading, setLoading] = react.useState(true);
9
+ const [error, setError] = react.useState(null);
10
+ react.useEffect(() => {
11
+ let active = true;
12
+ async function execute() {
13
+ setLoading(true);
14
+ setError(null);
15
+ try {
16
+ const result = await Component(props);
17
+ if (active) {
18
+ setContent(result);
19
+ }
20
+ }
21
+ catch (err) {
22
+ if (active) {
23
+ setError(err instanceof Error ? err : new Error("Unknown error"));
24
+ }
25
+ }
26
+ finally {
27
+ if (active) {
28
+ setLoading(false);
29
+ }
30
+ }
31
+ }
32
+ execute();
33
+ return () => {
34
+ active = false;
35
+ };
36
+ }, [props]);
37
+ if (isLoading)
38
+ return null;
39
+ if (error)
40
+ throw error;
41
+ return content;
42
+ };
43
+ }
44
+
45
+ exports.withSync = withSync;
46
+ //# sourceMappingURL=withSync.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withSync.cjs","sources":["../src/withSync.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\r\n\r\ntype AsyncComponent<P> = (props: P) => Promise<React.ReactNode>;\r\n\r\nexport function withSync<P extends object>(Component: AsyncComponent<P>) {\r\n return function SyncComponent(props: P) {\r\n const [content, setContent] = useState<React.ReactNode>(null);\r\n const [isLoading, setLoading] = useState(true);\r\n const [error, setError] = useState<Error | null>(null);\r\n\r\n useEffect(() => {\r\n let active = true;\r\n\r\n async function execute() {\r\n setLoading(true);\r\n setError(null);\r\n\r\n try {\r\n const result = await Component(props);\r\n\r\n if (active) {\r\n setContent(result);\r\n }\r\n } catch (err) {\r\n if (active) {\r\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\r\n }\r\n } finally {\r\n if (active) {\r\n setLoading(false);\r\n }\r\n }\r\n }\r\n\r\n execute();\r\n\r\n return () => {\r\n active = false;\r\n };\r\n }, [props]);\r\n\r\n if (isLoading) return null;\r\n if (error) throw error;\r\n\r\n return content;\r\n };\r\n}\r\n"],"names":["useState","useEffect"],"mappings":";;;;AAIM,SAAU,QAAQ,CAAmB,SAA4B,EAAA;IACrE,OAAO,SAAS,aAAa,CAAC,KAAQ,EAAA;QACpC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAGA,cAAQ,CAAkB,IAAI,CAAC,CAAC;QAC9D,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,GAAGA,cAAQ,CAAC,IAAI,CAAC,CAAC;QAC/C,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAGA,cAAQ,CAAe,IAAI,CAAC,CAAC;QAEvDC,eAAS,CAAC,MAAK;YACb,IAAI,MAAM,GAAG,IAAI,CAAC;AAElB,YAAA,eAAe,OAAO,GAAA;gBACpB,UAAU,CAAC,IAAI,CAAC,CAAC;gBACjB,QAAQ,CAAC,IAAI,CAAC,CAAC;gBAEf,IAAI;AACF,oBAAA,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC;AAEtC,oBAAA,IAAI,MAAM,EAAE;wBACV,UAAU,CAAC,MAAM,CAAC,CAAC;AACpB,oBAAA,CAAA;AACF,gBAAA,CAAA;AAAC,gBAAA,OAAO,GAAG,EAAE;AACZ,oBAAA,IAAI,MAAM,EAAE;AACV,wBAAA,QAAQ,CAAC,GAAG,YAAY,KAAK,GAAG,GAAG,GAAG,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;AACnE,oBAAA,CAAA;AACF,gBAAA,CAAA;AAAS,wBAAA;AACR,oBAAA,IAAI,MAAM,EAAE;wBACV,UAAU,CAAC,KAAK,CAAC,CAAC;AACnB,oBAAA,CAAA;AACF,gBAAA,CAAA;YACH,CAAC;AAED,YAAA,OAAO,EAAE,CAAC;AAEV,YAAA,OAAO,MAAK;gBACV,MAAM,GAAG,KAAK,CAAC;AACjB,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AAEZ,QAAA,IAAI,SAAS;AAAE,YAAA,OAAO,IAAI,CAAC;AAC3B,QAAA,IAAI,KAAK;AAAE,YAAA,MAAM,KAAK,CAAC;AAEvB,QAAA,OAAO,OAAO,CAAC;AACjB,IAAA,CAAC,CAAC;AACJ;;"}
package/withSync.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import * as react from 'react';
2
+
3
+ type AsyncComponent<P> = (props: P) => Promise<React.ReactNode>;
4
+ declare function withSync<P extends object>(Component: AsyncComponent<P>): (props: P) => react.ReactNode;
5
+
6
+ export { withSync };
package/withSync.js ADDED
@@ -0,0 +1,44 @@
1
+ import { useState, useEffect } from 'react';
2
+
3
+ function withSync(Component) {
4
+ return function SyncComponent(props) {
5
+ const [content, setContent] = useState(null);
6
+ const [isLoading, setLoading] = useState(true);
7
+ const [error, setError] = useState(null);
8
+ useEffect(() => {
9
+ let active = true;
10
+ async function execute() {
11
+ setLoading(true);
12
+ setError(null);
13
+ try {
14
+ const result = await Component(props);
15
+ if (active) {
16
+ setContent(result);
17
+ }
18
+ }
19
+ catch (err) {
20
+ if (active) {
21
+ setError(err instanceof Error ? err : new Error("Unknown error"));
22
+ }
23
+ }
24
+ finally {
25
+ if (active) {
26
+ setLoading(false);
27
+ }
28
+ }
29
+ }
30
+ execute();
31
+ return () => {
32
+ active = false;
33
+ };
34
+ }, [props]);
35
+ if (isLoading)
36
+ return null;
37
+ if (error)
38
+ throw error;
39
+ return content;
40
+ };
41
+ }
42
+
43
+ export { withSync };
44
+ //# sourceMappingURL=withSync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withSync.js","sources":["../src/withSync.ts"],"sourcesContent":["import { useEffect, useState } from \"react\";\r\n\r\ntype AsyncComponent<P> = (props: P) => Promise<React.ReactNode>;\r\n\r\nexport function withSync<P extends object>(Component: AsyncComponent<P>) {\r\n return function SyncComponent(props: P) {\r\n const [content, setContent] = useState<React.ReactNode>(null);\r\n const [isLoading, setLoading] = useState(true);\r\n const [error, setError] = useState<Error | null>(null);\r\n\r\n useEffect(() => {\r\n let active = true;\r\n\r\n async function execute() {\r\n setLoading(true);\r\n setError(null);\r\n\r\n try {\r\n const result = await Component(props);\r\n\r\n if (active) {\r\n setContent(result);\r\n }\r\n } catch (err) {\r\n if (active) {\r\n setError(err instanceof Error ? err : new Error(\"Unknown error\"));\r\n }\r\n } finally {\r\n if (active) {\r\n setLoading(false);\r\n }\r\n }\r\n }\r\n\r\n execute();\r\n\r\n return () => {\r\n active = false;\r\n };\r\n }, [props]);\r\n\r\n if (isLoading) return null;\r\n if (error) throw error;\r\n\r\n return content;\r\n };\r\n}\r\n"],"names":[],"mappings":";;AAIM,SAAU,QAAQ,CAAmB,SAA4B,EAAA;IACrE,OAAO,SAAS,aAAa,CAAC,KAAQ,EAAA;QACpC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAkB,IAAI,CAAC,CAAC;QAC9D,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC/C,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,QAAQ,CAAe,IAAI,CAAC,CAAC;QAEvD,SAAS,CAAC,MAAK;YACb,IAAI,MAAM,GAAG,IAAI,CAAC;AAElB,YAAA,eAAe,OAAO,GAAA;gBACpB,UAAU,CAAC,IAAI,CAAC,CAAC;gBACjB,QAAQ,CAAC,IAAI,CAAC,CAAC;gBAEf,IAAI;AACF,oBAAA,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,KAAK,CAAC,CAAC;AAEtC,oBAAA,IAAI,MAAM,EAAE;wBACV,UAAU,CAAC,MAAM,CAAC,CAAC;AACpB,oBAAA,CAAA;AACF,gBAAA,CAAA;AAAC,gBAAA,OAAO,GAAG,EAAE;AACZ,oBAAA,IAAI,MAAM,EAAE;AACV,wBAAA,QAAQ,CAAC,GAAG,YAAY,KAAK,GAAG,GAAG,GAAG,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;AACnE,oBAAA,CAAA;AACF,gBAAA,CAAA;AAAS,wBAAA;AACR,oBAAA,IAAI,MAAM,EAAE;wBACV,UAAU,CAAC,KAAK,CAAC,CAAC;AACnB,oBAAA,CAAA;AACF,gBAAA,CAAA;YACH,CAAC;AAED,YAAA,OAAO,EAAE,CAAC;AAEV,YAAA,OAAO,MAAK;gBACV,MAAM,GAAG,KAAK,CAAC;AACjB,YAAA,CAAC,CAAC;AACJ,QAAA,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AAEZ,QAAA,IAAI,SAAS;AAAE,YAAA,OAAO,IAAI,CAAC;AAC3B,QAAA,IAAI,KAAK;AAAE,YAAA,MAAM,KAAK,CAAC;AAEvB,QAAA,OAAO,OAAO,CAAC;AACjB,IAAA,CAAC,CAAC;AACJ;;"}
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;;"}