Skip to content

Commit 1b7a703

Browse files
Added internal states support;
1 parent d85e134 commit 1b7a703

9 files changed

+610
-76
lines changed

README.md

+63-35
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,34 @@ To fix, cancel all subscriptions and asynchronous task in "a useEffect cleanup f
3535
It uses [c-promise2](https://www.npmjs.com/package/c-promise2) to make it work.
3636
When used in conjunction with other libraries from CPromise ecosystem,
3737
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.
3939

4040
`useAsyncEffect` & `useAsyncCallback` hooks make cancelable async functions from generators,
4141
providing the ability to cancel async sequence in any stage in automatically way, when the related component unmounting.
4242
It's totally the same as async functions, but with cancellation- you need use 'yield' instead of 'await'. That's all.
4343

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+
4566
````jsx
4667
import React from "react";
4768
import {useState} from "react";
@@ -63,33 +84,6 @@ function JSONViewer(props) {
6384
````
6485
Notice: the related network request will be aborted, when unmounting.
6586

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-
9387
Live search for character from the `rickandmorty` universe using `rickandmortyapi.com`:
9488

9589
[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) {
253247

254248
To learn more about available features, see the c-promise2 [documentation](https://www.npmjs.com/package/c-promise2).
255249

250+
### Wiki
251+
252+
See the [Project Wiki](https://github.com/DigitalBrainJS/use-async-effect/wiki) to get the most exhaustive guide.
253+
256254
## Playground
257255

258256
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.
268266
The generator can return a cleanup function similar to the `useEffect` hook.
269267
- `generatorFn(scope: CPromise)` : `GeneratorFunction` - generator to resolve as an async function.
270268
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
273273
- `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+
````
274287

275288
### useAsyncCallback(generatorFn, deps?: []): CPromiseAsyncFunction
276289
### useAsyncCallback(generatorFn, options?: object): CPromiseAsyncFunction
277290
This hook makes an async callback that can be automatically canceled on unmount or by user request.
278291
- `generatorFn([scope: CPromise], ...userArguments)` : `GeneratorFunction` - generator to resolve as an async function.
279292
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:
282295
- `deps: any[]` - effect dependencies
283296
- `combine:boolean` - subscribe to the result of the async function already
284297
running with the same arguments or run a new one.
285298
- `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.
287300
- `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+
````
289316

290317
## Related projects
291318
- [c-promise2](https://www.npmjs.com/package/c-promise2) - promise with cancellation, decorators, timeouts, progress capturing, pause and user signals support
292319
- [cp-axios](https://www.npmjs.com/package/cp-axios) - a simple axios wrapper that provides an advanced cancellation api
293320
- [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
294322

295323
## License
296324

0 commit comments

Comments
 (0)