@ahoo-wang/fetcher-react 2.6.2 → 2.6.5

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,6 +129,64 @@ const MyComponent = () => {
92
129
  };
93
130
  ```
94
131
 
132
+ ### usePromiseState Hook
133
+
134
+ The `usePromiseState` hook provides state management for promise operations without execution logic. Supports both
135
+ static options and dynamic option suppliers.
136
+
137
+ ```typescript jsx
138
+ import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';
139
+
140
+ const MyComponent = () => {
141
+ const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();
142
+
143
+ const handleSuccess = () => setSuccess('Data loaded');
144
+ const handleError = () => setError(new Error('Failed to load'));
145
+
146
+ return (
147
+ <div>
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>
185
+ </div>
186
+ );
187
+ };
188
+ ```
189
+
95
190
  ### useRequestId Hook
96
191
 
97
192
  The `useRequestId` hook provides request ID management for preventing race conditions in async operations.
@@ -127,27 +222,28 @@ const MyComponent = () => {
127
222
  };
128
223
  ```
129
224
 
130
- ### useFetcher Hook
225
+ ### useLatest Hook
131
226
 
132
- 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.
133
229
 
134
230
  ```typescript jsx
135
- import { useFetcher } from '@ahoo-wang/fetcher-react';
231
+ import { useLatest } from '@ahoo-wang/fetcher-react';
136
232
 
137
233
  const MyComponent = () => {
138
- const { loading, error, result, execute } = useFetcher<string>();
234
+ const [count, setCount] = useState(0);
235
+ const latestCount = useLatest(count);
139
236
 
140
- const handleFetch = () => {
141
- execute({ url: '/api/users', method: 'GET' });
237
+ const handleAsync = async () => {
238
+ await someAsyncOperation();
239
+ console.log('Latest count:', latestCount.current); // Always the latest
142
240
  };
143
241
 
144
- if (loading) return <div>Loading...</div>;
145
- if (error) return <div>Error: {error.message}</div>;
146
-
147
242
  return (
148
243
  <div>
149
- <pre>{JSON.stringify(result, null, 2)}</pre>
150
- <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>
151
247
  </div>
152
248
  );
153
249
  };
@@ -204,19 +300,26 @@ const [user, setUser] = useKeyStorage(userStorage);
204
300
 
205
301
  ## API Reference
206
302
 
207
- ### usePromiseState
303
+ ### useFetcher
208
304
 
209
305
  ```typescript
210
- function usePromiseState<R = unknown>(
211
- options?: UsePromiseStateOptions<R>,
212
- ): UsePromiseStateReturn<R>;
306
+ function useFetcher<R = unknown, E = unknown>(
307
+ options?: UseFetcherOptions<R, E> | UseFetcherOptionsSupplier<R, E>,
308
+ ): UseFetcherReturn<R, E>;
213
309
  ```
214
310
 
215
- 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`)
216
318
 
217
319
  **Parameters:**
218
320
 
219
- - `options`: Configuration options
321
+ - `options`: Configuration options or supplier function
322
+ - `fetcher`: Custom fetcher instance to use. Defaults to the default fetcher.
220
323
  - `initialStatus`: Initial status, defaults to IDLE
221
324
  - `onSuccess`: Callback invoked on success
222
325
  - `onError`: Callback invoked on error
@@ -229,37 +332,86 @@ An object containing:
229
332
  - `loading`: Indicates if currently loading
230
333
  - `result`: The result value
231
334
  - `error`: The error value
232
- - `setLoading`: Set status to LOADING
233
- - `setSuccess`: Set status to SUCCESS with result
234
- - `setError`: Set status to ERROR with error
235
- - `setIdle`: Set status to IDLE
335
+ - `exchange`: The FetchExchange object representing the ongoing fetch operation
336
+ - `execute`: Function to execute a fetch request
236
337
 
237
338
  ### useExecutePromise
238
339
 
239
340
  ```typescript
240
- function useExecutePromise<R = unknown>(): UseExecutePromiseReturn<R>;
341
+ function useExecutePromise<R = unknown, E = unknown>(
342
+ options?: UseExecutePromiseOptions<R, E>,
343
+ ): UseExecutePromiseReturn<R, E>;
241
344
  ```
242
345
 
243
- 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
244
360
 
245
361
  **Returns:**
246
362
 
247
363
  An object containing:
248
364
 
249
- - `status`: Current status
365
+ - `status`: Current status (IDLE, LOADING, SUCCESS, ERROR)
250
366
  - `loading`: Indicates if currently loading
251
367
  - `result`: The result value
252
368
  - `error`: The error value
253
369
  - `execute`: Function to execute a promise supplier or promise
254
370
  - `reset`: Function to reset the state to initial values
255
371
 
372
+ ### usePromiseState
373
+
374
+ ```typescript
375
+ function usePromiseState<R = unknown, E = unknown>(
376
+ options?: UsePromiseStateOptions<R, E> | UsePromiseStateOptionsSupplier<R, E>,
377
+ ): UsePromiseStateReturn<R, E>;
378
+ ```
379
+
380
+ A React hook for managing promise state without execution logic. Supports both static options and dynamic option
381
+ suppliers.
382
+
383
+ **Type Parameters:**
384
+
385
+ - `R`: The type of the result
386
+ - `E`: The type of the error (defaults to `unknown`)
387
+
388
+ **Parameters:**
389
+
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)
394
+
395
+ **Returns:**
396
+
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
407
+
256
408
  ### useRequestId
257
409
 
258
410
  ```typescript
259
411
  function useRequestId(): UseRequestIdReturn;
260
412
  ```
261
413
 
262
- 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.
263
415
 
264
416
  **Returns:**
265
417
 
@@ -271,29 +423,26 @@ An object containing:
271
423
  - `invalidate`: Invalidate current request ID (mark as stale)
272
424
  - `reset`: Reset request ID counter
273
425
 
274
- ### useFetcher
426
+ ### useLatest
275
427
 
276
428
  ```typescript
277
- function useFetcher<R>(options?: UseFetcherOptions): UseFetcherReturn<R>;
429
+ function useLatest<T>(value: T): { current: T };
278
430
  ```
279
431
 
280
- 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
281
438
 
282
439
  **Parameters:**
283
440
 
284
- - `options`: Configuration options
285
- - `fetcher`: Custom fetcher instance to use. Defaults to the default fetcher.
441
+ - `value`: The value to track
286
442
 
287
443
  **Returns:**
288
444
 
289
- An object containing:
290
-
291
- - `status`: Current status
292
- - `loading`: Indicates if currently loading
293
- - `result`: The result value
294
- - `error`: The error value
295
- - `exchange`: The FetchExchange object
296
- - `execute`: Function to execute a fetch request
445
+ A ref object with a `current` property containing the latest value
297
446
 
298
447
  ### useKeyStorage
299
448