@@ -35,13 +35,34 @@ To fix, cancel all subscriptions and asynchronous task in "a useEffect cleanup f
35
35
It uses [ c-promise2] ( https://www.npmjs.com/package/c-promise2 ) to make it work.
36
36
When used in conjunction with other libraries from CPromise ecosystem,
37
37
such as [ cp-fetch] ( https://www.npmjs.com/package/cp-fetch ) and [ cp-axios] ( https://www.npmjs.com/package/cp-axios ) ,
38
- you get a powerful tool for building asynchronous logic for your React components.
38
+ you get a powerful tool for building asynchronous logic of React components.
39
39
40
40
` useAsyncEffect ` & ` useAsyncCallback ` hooks make cancelable async functions from generators,
41
41
providing the ability to cancel async sequence in any stage in automatically way, when the related component unmounting.
42
42
It's totally the same as async functions, but with cancellation- you need use 'yield' instead of 'await'. That's all.
43
43
44
- JSON fetching using ` useAsyncEffect ` [ Live demo] ( https://codesandbox.io/s/use-async-effect-fetch-tiny-ui-xbmk2?file=/src/TestComponent.js )
44
+ A tiny ` useAsyncEffect ` demo with JSON fetching using internal states:
45
+
46
+ [ Live demo to play] ( https://codesandbox.io/s/use-async-effect-fetch-tiny-ui-states-g5qd7 )
47
+
48
+ ```` javascript
49
+ export default function JSONViewer (props ) {
50
+ const [cancel , done , result ]= useAsyncEffect (function * (){
51
+ return (yield cpAxios (props .url )).data ;
52
+ }, {states: true })
53
+
54
+ return (
55
+ < div className= " component" >
56
+ < div className= " caption" > useAsyncEffect demo: < / div>
57
+ < div> {done? JSON .stringify (result) : " loading..." }< / div>
58
+ < button onClick= {cancel}> Cancel async effect< / button>
59
+ < / div>
60
+ );
61
+ }
62
+ ````
63
+
64
+ [ Another demo] ( https://codesandbox.io/s/use-async-effect-fetch-tiny-ui-xbmk2?file=/src/TestComponent.js )
65
+
45
66
```` jsx
46
67
import React from " react" ;
47
68
import {useState } from " react" ;
@@ -63,33 +84,6 @@ function JSONViewer(props) {
63
84
````
64
85
Notice: the related network request will be aborted, when unmounting.
65
86
66
- It can be even easier with the [ axios wrapper] ( https://www.npmjs.com/package/cp-axios ) ([ Demo] ( https://codesandbox.io/s/use-async-effect-axios-tiny-lsbpv?file=/src/TestComponent.js ) ):
67
- ```` javascript
68
- import React , { useState } from " react" ;
69
- import { useAsyncEffect } from " use-async-effect2" ;
70
- import cpAxios from " cp-axios" ;
71
-
72
- export default function TestComponent (props ) {
73
- const [text , setText ] = useState (" " );
74
-
75
- const cancel = useAsyncEffect (
76
- function * () {
77
- const response = yield cpAxios (props .url );
78
- setText (JSON .stringify (response .data ));
79
- },
80
- [props .url ]
81
- );
82
-
83
- return (
84
- < div className= " component" >
85
- < div className= " caption" > useAsyncEffect demo: < / div>
86
- < div> {text}< / div>
87
- < button onClick= {cancel}> Cancel request< / button>
88
- < / div>
89
- );
90
- }
91
- ````
92
-
93
87
Live search for character from the ` rickandmorty ` universe using ` rickandmortyapi.com ` :
94
88
95
89
[ Live demo] ( https://codesandbox.io/s/use-async-effect-axios-rickmorty-search-ui-sd2mv?file=/src/TestComponent.js )
@@ -253,6 +247,10 @@ export default function TestComponent(props) {
253
247
254
248
To learn more about available features, see the c- promise2 [documentation](https: // www.npmjs.com/package/c-promise2).
255
249
250
+ ### Wiki
251
+
252
+ See the [Project Wiki](https: // github.com/DigitalBrainJS/use-async-effect/wiki) to get the most exhaustive guide.
253
+
256
254
## Playground
257
255
258
256
To get it, clone the repository and run ` npm run playground` in the project directory or
@@ -268,29 +266,59 @@ the effect cleanup process started before it completes.
268
266
The generator can return a cleanup function similar to the `useEffect` hook.
269
267
- `generatorFn (scope : CPromise )` : `GeneratorFunction` - generator to resolve as an async function.
270
268
Generator context (`this`) refers to the CPromise instance.
271
- - `deps?: any[]` - effect dependencies
272
- - `options.deps?: any[]` - skip the first render
269
+ - `deps?: any[] | UseAsyncEffectOptions` - effect dependencies
270
+
271
+ #### UseAsyncEffectOptions:
272
+ - `options.deps?: any[]` - effect dependencies
273
273
- `options.skipFirst?: boolean` - skip first render
274
+ - `options.states: boolean= false` - use states
275
+
276
+ #### Available states vars:
277
+ - `done: boolean` - the function execution is completed (with success or failure)
278
+ - `result: any` - refers to the resolved function result
279
+ - `error: object` - refers to the error object. This var is always set when an error occurs.
280
+ - `canceled:boolean` - is set to true if the function has been failed with a `CanceledError`.
281
+
282
+ All these vars are defined on the returned `cancelFn` function and can be alternative reached through
283
+ the iterator interface in the following order:
284
+ ````javascript
285
+ const [cancelFn, done, result, error, canceled]= useAsyncEffect(/* code*/ );
286
+ ````
274
287
275
288
### useAsyncCallback(generatorFn, deps?: []): CPromiseAsyncFunction
276
289
### useAsyncCallback(generatorFn, options?: object): CPromiseAsyncFunction
277
290
This hook makes an async callback that can be automatically canceled on unmount or by user request.
278
291
- `generatorFn([scope: CPromise], ...userArguments)` : `GeneratorFunction` - generator to resolve as an async function.
279
292
Generator context (`this`) and the first argument (if `options.scopeArg` is set) refer to the CPromise instance.
280
-
281
- #### options :
293
+ - `deps?: any[] | UseAsyncCallbackOptions` - effect dependencies
294
+ #### UseAsyncCallbackOptions :
282
295
- `deps: any[]` - effect dependencies
283
296
- `combine:boolean` - subscribe to the result of the async function already
284
297
running with the same arguments or run a new one.
285
298
- `cancelPrevious:boolean` - cancel the previous pending async function before running a new one.
286
- - `concurrency : number=0` - set concurrency limit for simultaneous calls. `0` mean unlimited.
299
+ - `threads : number=0` - set concurrency limit for simultaneous calls. `0` mean unlimited.
287
300
- `queueSize: number=0` - set max queue size.
288
- - `scopeArg: boolean=false` - pass CPromise scope to the generator function as the first argument.
301
+ - `scopeArg: boolean=false` - pass `CPromise` scope to the generator function as the first argument.
302
+ - `states: boolean=false` - enable state changing. The function must be single threaded to use the states.
303
+
304
+ #### Available states vars:
305
+ - `pending: boolean` - the function is in the pending state
306
+ - `done: boolean` - the function execution is completed (with success or failure)
307
+ - `result: any` - refers to the resolved function result
308
+ - `error: object` - refers to the error object. This var is always set when an error occurs.
309
+ - `canceled:boolean` - is set to true if the function has been failed with a `CanceledError`.
310
+
311
+ All these vars are defined on the decorated function and can be alternative reached through
312
+ the iterator interface in the following order:
313
+ ````javascript
314
+ const [decoratedFn, cancelFn, pending, done, result, error, canceled]= useAsyncCallback(/* code*/ );
315
+ ````
289
316
290
317
## Related projects
291
318
- [c-promise2](https:// www.npmjs.com/package/c-promise2) - promise with cancellation, decorators, timeouts, progress capturing, pause and user signals support
292
319
- [cp-axios](https:// www.npmjs.com/package/cp-axios) - a simple axios wrapper that provides an advanced cancellation api
293
320
- [cp-fetch](https:// www.npmjs.com/package/cp-fetch) - fetch with timeouts and request cancellation
321
+ - [cp-koa](https:// www.npmjs.com/package/cp-koa) - koa with middlewares cancellation
294
322
295
323
## License
296
324
0 commit comments