@ahoo-wang/fetcher-react 2.6.3 → 2.6.6

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/README.md CHANGED
@@ -13,11 +13,25 @@ automatic re-rendering and loading states.
13
13
 
14
14
  ## Features
15
15
 
16
- - 🔄 **React Hooks**: Provides React hooks for seamless integration with Fetcher
17
- - 🌐 **TypeScript Support**: Full TypeScript support with comprehensive type definitions
18
- - 🚀 **Modern**: Built with modern React patterns and best practices
19
- - 🧠 **Smart Caching**: Built-in caching and automatic revalidation
20
- - **Promise State Management**: Hooks for managing async operations and promise states
16
+ - 🚀 **Data Fetching**: Complete HTTP client integration with React hooks
17
+ - 🔄 **Promise State Management**: Advanced async operation handling with race condition protection
18
+ - 🛡️ **Type Safety**: Full TypeScript support with comprehensive type definitions
19
+ - **Performance**: Optimized with useMemo, useCallback, and smart dependency management
20
+ - 🎯 **Options Flexibility**: Support for both static options and dynamic option suppliers
21
+ - 🔧 **Developer Experience**: Built-in loading states, error handling, and automatic re-rendering
22
+
23
+ ## Table of Contents
24
+
25
+ - [Installation](#installation)
26
+ - [Usage](#usage)
27
+ - [useFetcher Hook](#usefetcher-hook)
28
+ - [useExecutePromise Hook](#useexecutepromise-hook)
29
+ - [usePromiseState Hook](#usepromisestate-hook)
30
+ - [useRequestId Hook](#userequestid-hook)
31
+ - [useLatest Hook](#uselatest-hook)
32
+ - [useKeyStorage Hook](#usekeystorage-hook)
33
+ - [API Reference](#api-reference)
34
+ - [License](#license)
21
35
 
22
36
  ## Installation
23
37
 
@@ -25,30 +39,53 @@ automatic re-rendering and loading states.
25
39
  npm install @ahoo-wang/fetcher-react
26
40
  ```
27
41
 
42
+ ## Quick Start
43
+
44
+ Get started with `@ahoo-wang/fetcher-react` in just a few lines:
45
+
46
+ ```typescript jsx
47
+ import { useFetcher } from '@ahoo-wang/fetcher-react';
48
+
49
+ function App() {
50
+ const { loading, result, error, execute } = useFetcher();
51
+
52
+ return (
53
+ <div>
54
+ <button onClick={() => execute({ url: '/api/data', method: 'GET' })}>
55
+ Fetch Data
56
+ </button>
57
+ {loading && <p>Loading...</p>}
58
+ {result && <pre>{JSON.stringify(result, null, 2)}</pre>}
59
+ {error && <p>Error: {error.message}</p>}
60
+ </div>
61
+ );
62
+ }
63
+ ```
64
+
28
65
  ## Usage
29
66
 
30
- ### usePromiseState Hook
67
+ ### useFetcher Hook
31
68
 
32
- The `usePromiseState` hook provides state management for promise operations without execution logic.
69
+ The `useFetcher` hook provides complete data fetching capabilities with automatic state management, race condition
70
+ protection, and flexible configuration options.
33
71
 
34
72
  ```typescript jsx
35
- import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';
73
+ import { useFetcher } from '@ahoo-wang/fetcher-react';
36
74
 
37
75
  const MyComponent = () => {
38
- const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();
76
+ const { loading, error, result, execute } = useFetcher<string>();
39
77
 
40
- const handleSuccess = () => setSuccess('Data loaded');
41
- const handleError = () => setError(new Error('Failed to load'));
78
+ const handleFetch = () => {
79
+ execute({ url: '/api/users', method: 'GET' });
80
+ };
81
+
82
+ if (loading) return <div>Loading...</div>;
83
+ if (error) return <div>Error: {error.message}</div>;
42
84
 
43
85
  return (
44
86
  <div>
45
- <button onClick={handleSuccess}>Set Success</button>
46
- <button onClick={handleError}>Set Error</button>
47
- <button onClick={setIdle}>Reset</button>
48
- <p>Status: {status}</p>
49
- {loading && <p>Loading...</p>}
50
- {result && <p>Result: {result}</p>}
51
- {error && <p>Error: {error.message}</p>}
87
+ <pre>{JSON.stringify(result, null, 2)}</pre>
88
+ <button onClick={handleFetch}>Fetch Data</button>
52
89
  </div>
53
90
  );
54
91
  };
@@ -56,8 +93,8 @@ const MyComponent = () => {
56
93
 
57
94
  ### useExecutePromise Hook
58
95
 
59
- The `useExecutePromise` hook manages asynchronous operations with automatic state handling and built-in race condition
60
- protection.
96
+ The `useExecutePromise` hook manages asynchronous operations with automatic state handling, built-in race condition
97
+ protection, and support for promise state options.
61
98
 
62
99
  ```typescript jsx
63
100
  import { useExecutePromise } from '@ahoo-wang/fetcher-react';
@@ -92,27 +129,59 @@ const MyComponent = () => {
92
129
  };
93
130
  ```
94
131
 
95
- ### useLatest Hook
132
+ ### usePromiseState Hook
96
133
 
97
- The `useLatest` hook returns the latest value, useful for accessing the current value in async callbacks.
134
+ The `usePromiseState` hook provides state management for promise operations without execution logic. Supports both
135
+ static options and dynamic option suppliers.
98
136
 
99
137
  ```typescript jsx
100
- import { useLatest } from '@ahoo-wang/fetcher-react';
138
+ import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';
101
139
 
102
140
  const MyComponent = () => {
103
- const [count, setCount] = useState(0);
104
- const latestCount = useLatest(count);
141
+ const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();
105
142
 
106
- const handleAsync = async () => {
107
- await someAsyncOperation();
108
- console.log('Latest count:', latestCount.current); // Always the latest
109
- };
143
+ const handleSuccess = () => setSuccess('Data loaded');
144
+ const handleError = () => setError(new Error('Failed to load'));
110
145
 
111
146
  return (
112
147
  <div>
113
- <p>Count: {count}</p>
114
- <button onClick={() => setCount(c => c + 1)}>Increment</button>
115
- <button onClick={handleAsync}>Async Log</button>
148
+ <button onClick={handleSuccess}>Set Success</button>
149
+ <button onClick={handleError}>Set Error</button>
150
+ <button onClick={setIdle}>Reset</button>
151
+ <p>Status: {status}</p>
152
+ {loading && <p>Loading...</p>}
153
+ {result && <p>Result: {result}</p>}
154
+ {error && <p>Error: {error.message}</p>}
155
+ </div>
156
+ );
157
+ };
158
+ ```
159
+
160
+ #### usePromiseState with Options Supplier
161
+
162
+ ```typescript jsx
163
+ import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';
164
+
165
+ const MyComponent = () => {
166
+ // Using options supplier for dynamic configuration
167
+ const optionsSupplier = () => ({
168
+ initialStatus: PromiseStatus.IDLE,
169
+ onSuccess: async (result: string) => {
170
+ await saveToAnalytics(result);
171
+ console.log('Success:', result);
172
+ },
173
+ onError: async (error) => {
174
+ await logErrorToServer(error);
175
+ console.error('Error:', error);
176
+ },
177
+ });
178
+
179
+ const { setSuccess, setError } = usePromiseState<string>(optionsSupplier);
180
+
181
+ return (
182
+ <div>
183
+ <button onClick={() => setSuccess('Dynamic success!')}>Set Success</button>
184
+ <button onClick={() => setError(new Error('Dynamic error!'))}>Set Error</button>
116
185
  </div>
117
186
  );
118
187
  };
@@ -153,27 +222,28 @@ const MyComponent = () => {
153
222
  };
154
223
  ```
155
224
 
156
- ### useFetcher Hook
225
+ ### useLatest Hook
157
226
 
158
- The `useFetcher` hook provides data fetching capabilities with automatic state management.
227
+ The `useLatest` hook returns a ref containing the latest value, useful for accessing the current value in async
228
+ callbacks.
159
229
 
160
230
  ```typescript jsx
161
- import { useFetcher } from '@ahoo-wang/fetcher-react';
231
+ import { useLatest } from '@ahoo-wang/fetcher-react';
162
232
 
163
233
  const MyComponent = () => {
164
- const { loading, error, result, execute } = useFetcher<string>();
234
+ const [count, setCount] = useState(0);
235
+ const latestCount = useLatest(count);
165
236
 
166
- const handleFetch = () => {
167
- execute({ url: '/api/users', method: 'GET' });
237
+ const handleAsync = async () => {
238
+ await someAsyncOperation();
239
+ console.log('Latest count:', latestCount.current); // Always the latest
168
240
  };
169
241
 
170
- if (loading) return <div>Loading...</div>;
171
- if (error) return <div>Error: {error.message}</div>;
172
-
173
242
  return (
174
243
  <div>
175
- <pre>{JSON.stringify(result, null, 2)}</pre>
176
- <button onClick={handleFetch}>Fetch Data</button>
244
+ <p>Count: {count}</p>
245
+ <button onClick={() => setCount(c => c + 1)}>Increment</button>
246
+ <button onClick={handleAsync}>Async Log</button>
177
247
  </div>
178
248
  );
179
249
  };
@@ -230,19 +300,26 @@ const [user, setUser] = useKeyStorage(userStorage);
230
300
 
231
301
  ## API Reference
232
302
 
233
- ### usePromiseState
303
+ ### useFetcher
234
304
 
235
305
  ```typescript
236
- function usePromiseState<R = unknown>(
237
- options?: UsePromiseStateOptions<R>,
238
- ): UsePromiseStateReturn<R>;
306
+ function useFetcher<R = unknown, E = unknown>(
307
+ options?: UseFetcherOptions<R, E> | UseFetcherOptionsSupplier<R, E>,
308
+ ): UseFetcherReturn<R, E>;
239
309
  ```
240
310
 
241
- A React hook for managing promise state without execution logic.
311
+ A React hook for managing asynchronous fetch operations with proper state handling, race condition protection, and
312
+ flexible configuration.
313
+
314
+ **Type Parameters:**
315
+
316
+ - `R`: The type of the result
317
+ - `E`: The type of the error (defaults to `unknown`)
242
318
 
243
319
  **Parameters:**
244
320
 
245
- - `options`: Configuration options
321
+ - `options`: Configuration options or supplier function
322
+ - `fetcher`: Custom fetcher instance to use. Defaults to the default fetcher.
246
323
  - `initialStatus`: Initial status, defaults to IDLE
247
324
  - `onSuccess`: Callback invoked on success
248
325
  - `onError`: Callback invoked on error
@@ -255,49 +332,78 @@ An object containing:
255
332
  - `loading`: Indicates if currently loading
256
333
  - `result`: The result value
257
334
  - `error`: The error value
258
- - `setLoading`: Set status to LOADING
259
- - `setSuccess`: Set status to SUCCESS with result
260
- - `setError`: Set status to ERROR with error
261
- - `setIdle`: Set status to IDLE
335
+ - `exchange`: The FetchExchange object representing the ongoing fetch operation
336
+ - `execute`: Function to execute a fetch request
262
337
 
263
338
  ### useExecutePromise
264
339
 
265
340
  ```typescript
266
- function useExecutePromise<R = unknown>(): UseExecutePromiseReturn<R>;
341
+ function useExecutePromise<R = unknown, E = unknown>(
342
+ options?: UseExecutePromiseOptions<R, E>,
343
+ ): UseExecutePromiseReturn<R, E>;
267
344
  ```
268
345
 
269
- A React hook for managing asynchronous operations with proper state handling.
346
+ A React hook for managing asynchronous operations with proper state handling, race condition protection, and promise
347
+ state options.
348
+
349
+ **Type Parameters:**
350
+
351
+ - `R`: The type of the result
352
+ - `E`: The type of the error (defaults to `unknown`)
353
+
354
+ **Parameters:**
355
+
356
+ - `options`: Configuration options
357
+ - `initialStatus`: Initial status, defaults to IDLE
358
+ - `onSuccess`: Callback invoked on success
359
+ - `onError`: Callback invoked on error
270
360
 
271
361
  **Returns:**
272
362
 
273
363
  An object containing:
274
364
 
275
- - `status`: Current status
365
+ - `status`: Current status (IDLE, LOADING, SUCCESS, ERROR)
276
366
  - `loading`: Indicates if currently loading
277
367
  - `result`: The result value
278
368
  - `error`: The error value
279
369
  - `execute`: Function to execute a promise supplier or promise
280
370
  - `reset`: Function to reset the state to initial values
281
371
 
282
- ### useLatest
372
+ ### usePromiseState
283
373
 
284
374
  ```typescript
285
- function useLatest<T>(value: T): T;
375
+ function usePromiseState<R = unknown, E = unknown>(
376
+ options?: UsePromiseStateOptions<R, E> | UsePromiseStateOptionsSupplier<R, E>,
377
+ ): UsePromiseStateReturn<R, E>;
286
378
  ```
287
379
 
288
- A React hook that returns the latest value, useful for accessing the current value in async callbacks.
380
+ A React hook for managing promise state without execution logic. Supports both static options and dynamic option
381
+ suppliers.
289
382
 
290
383
  **Type Parameters:**
291
384
 
292
- - `T`: The type of the value
385
+ - `R`: The type of the result
386
+ - `E`: The type of the error (defaults to `unknown`)
293
387
 
294
388
  **Parameters:**
295
389
 
296
- - `value`: The value to track
390
+ - `options`: Configuration options or supplier function
391
+ - `initialStatus`: Initial status, defaults to IDLE
392
+ - `onSuccess`: Callback invoked on success (can be async)
393
+ - `onError`: Callback invoked on error (can be async)
297
394
 
298
395
  **Returns:**
299
396
 
300
- The latest value
397
+ An object containing:
398
+
399
+ - `status`: Current status (IDLE, LOADING, SUCCESS, ERROR)
400
+ - `loading`: Indicates if currently loading
401
+ - `result`: The result value
402
+ - `error`: The error value
403
+ - `setLoading`: Set status to LOADING
404
+ - `setSuccess`: Set status to SUCCESS with result
405
+ - `setError`: Set status to ERROR with error
406
+ - `setIdle`: Set status to IDLE
301
407
 
302
408
  ### useRequestId
303
409
 
@@ -305,7 +411,7 @@ The latest value
305
411
  function useRequestId(): UseRequestIdReturn;
306
412
  ```
307
413
 
308
- A React hook for managing request IDs and race condition protection.
414
+ A React hook for managing request IDs and race condition protection in async operations.
309
415
 
310
416
  **Returns:**
311
417
 
@@ -317,29 +423,26 @@ An object containing:
317
423
  - `invalidate`: Invalidate current request ID (mark as stale)
318
424
  - `reset`: Reset request ID counter
319
425
 
320
- ### useFetcher
426
+ ### useLatest
321
427
 
322
428
  ```typescript
323
- function useFetcher<R>(options?: UseFetcherOptions): UseFetcherReturn<R>;
429
+ function useLatest<T>(value: T): { current: T };
324
430
  ```
325
431
 
326
- A React hook for managing asynchronous fetch operations with proper state handling.
432
+ A React hook that returns a ref object containing the latest value, useful for accessing the current value in async
433
+ callbacks.
434
+
435
+ **Type Parameters:**
436
+
437
+ - `T`: The type of the value
327
438
 
328
439
  **Parameters:**
329
440
 
330
- - `options`: Configuration options
331
- - `fetcher`: Custom fetcher instance to use. Defaults to the default fetcher.
441
+ - `value`: The value to track
332
442
 
333
443
  **Returns:**
334
444
 
335
- An object containing:
336
-
337
- - `status`: Current status
338
- - `loading`: Indicates if currently loading
339
- - `result`: The result value
340
- - `error`: The error value
341
- - `exchange`: The FetchExchange object
342
- - `execute`: Function to execute a fetch request
445
+ A ref object with a `current` property containing the latest value
343
446
 
344
447
  ### useKeyStorage
345
448