Skip to content

Commit 02e547c

Browse files
Updated README.md;
1 parent 0e960b3 commit 02e547c

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

README.md

+40-3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
- [Request aborting using Axios cancelToken](#request-aborting-using-axios-canceltoken)
1515
- [Using generators as async functions](#using-generators-as-async-functions)
1616
- [Abortable concurrent requests](#abortable-concurrent-requests)
17+
- [React usage](#react-usage)
1718
- [API Reference](#api-reference)
1819
- [Related projects](#related-projects)
1920
- [License](#license)
@@ -39,11 +40,11 @@ Starting from version `0.1.12` the package imports peer dependencies instead of
3940
So, you should install `c-promise2` and `axios` packages manually using the following command:
4041

4142
```bash
42-
$ npm install cp-axios c-promise2 axios
43+
$ npm install cp-axios
4344
```
4445

4546
```bash
46-
$ yarn add cp-axios c-promise2 axios
47+
$ yarn add cp-axios
4748
```
4849

4950
### CDN bundle
@@ -119,7 +120,7 @@ const cpAxios= require('cp-axios');
119120
const CPromise= require('c-promise2');
120121
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
121122

122-
const chain= CPromise.from(function*(){
123+
const chain= CPromise.run(function*(){
123124
try{
124125
const response= yield cpAxios(url).timeout(5000);
125126
console.log(`Done: `, response.data)
@@ -186,6 +187,42 @@ const promise = CPromise.all(
186187
// yeah, we able to cancel the entire task and abort pending network requests
187188
//setTimeout(() => promise.cancel(), 4500);
188189
````
190+
## React usage
191+
192+
`cpAxios` can be easily used with React using the [`useAsyncEffect`](https://www.npmjs.com/package/use-async-effect2) hook, which allows canceled asynchronous functions to be executed as effects ([Live Demo](https://codesandbox.io/s/use-async-effect-axios-minimal-pdngg?file=/src/TestComponent.js)):
193+
194+
```jsx
195+
import React from "react";
196+
import { useAsyncEffect } from "use-async-effect2";
197+
import cpAxios from "cp-axios";
198+
199+
/*
200+
Note: the related network request will also be aborted
201+
Check out your network console
202+
*/
203+
204+
function TestComponent({ url, timeout }) {
205+
const [cancel, done, result, err] = useAsyncEffect(
206+
function* () {
207+
return (yield cpAxios(url).timeout(timeout)).data;
208+
},
209+
{ states: true, deps: [url] }
210+
);
211+
212+
return (
213+
<div>
214+
{done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
215+
<button onClick={cancel} disabled={done}>
216+
Cancel async effect (abort request)
217+
</button>
218+
</div>
219+
);
220+
}
221+
222+
export default TestComponent;
223+
```
224+
225+
The request will be automatically aborted when the effect is canceled / restarted.
189226

190227
## API Reference
191228

0 commit comments

Comments
 (0)