|
| 1 | + |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +[](https://github.com/DigitalBrainJS/use-async-effect/stargazers) |
| 6 | + |
| 7 | +## useAsyncEffect2 |
| 8 | +The library provides a React hook with ability to automatically cancel asynchronous code inside it. |
| 9 | +It just makes it easier to write cancelable asynchronous code that doesn't cause |
| 10 | +the following React issue when unmounting, if your asynchronous tasks that change state are pending: |
| 11 | +```` |
| 12 | +Warning: Can't perform a React state update on an unmounted component. |
| 13 | +This is an no-op, but it indicates a memory leak in your application. |
| 14 | +To fix, cancel all subscriptions and asynchronous task in "a useEffect cleanup function". |
| 15 | +```` |
| 16 | +It uses [c-promise2](https://www.npmjs.com/package/c-promise2) to make it work. |
| 17 | +When it used in conjunction with other libraries that work with the CPromise, |
| 18 | +such as [cp-fetch](https://www.npmjs.com/package/cp-fetch) and [cp-axios](https://www.npmjs.com/package/cp-axios), |
| 19 | +you get a powerful tool for building asynchronous logic for your components. |
| 20 | +You just have to use `generators` instead of an async function to make your code cancellable, |
| 21 | +but basically, that just means you will have to use `yield` instead of `await` keyword. |
| 22 | +## Usage example |
| 23 | +Minimal example with json request [Live demo](https://codesandbox.io/s/friendly-murdock-wxq8u?file=/src/App.js) |
| 24 | +````jsx |
| 25 | +import React from "react"; |
| 26 | +import {useState} from "react"; |
| 27 | +import {useAsyncEffect} from "use-async-effect2"; |
| 28 | +import cpFetch from "cp-fetch"; |
| 29 | + |
| 30 | +function JSONViewer(props) { |
| 31 | + const [text, setText] = useState(""); |
| 32 | + |
| 33 | + useAsyncEffect(function* () { |
| 34 | + setText("fetching..."); |
| 35 | + const response = yield cpFetch(props.url); |
| 36 | + const json = yield response.json(); |
| 37 | + setText(`Success: ${JSON.stringify(json)}`); |
| 38 | + }, [props.url]); |
| 39 | + |
| 40 | + return <div>{text}</div>; |
| 41 | +} |
| 42 | +```` |
| 43 | +Example with timeout & error handling ([Live demo](https://codesandbox.io/s/async-effect-demo1-vho29)): |
| 44 | +````jsx |
| 45 | +import React from "react"; |
| 46 | +import {useState} from "react"; |
| 47 | +import {useAsyncEffect, E_REASON_UNMOUNTED} from "use-async-effect2"; |
| 48 | +import {CanceledError} from "c-promise2"; |
| 49 | +import cpFetch from "cp-fetch"; |
| 50 | + |
| 51 | +export default function TestComponent(props) { |
| 52 | + const [text, setText] = useState(""); |
| 53 | + |
| 54 | + const [cancel]= useAsyncEffect(function* ({onCancel}) { |
| 55 | + console.log("mount"); |
| 56 | + |
| 57 | + this.timeout(5000); |
| 58 | + |
| 59 | + onCancel(()=> console.log('scope canceled')); |
| 60 | + |
| 61 | + try { |
| 62 | + setText("fetching..."); |
| 63 | + const response = yield cpFetch(props.url); |
| 64 | + const json = yield response.json(); |
| 65 | + setText(`Success: ${JSON.stringify(json)}`); |
| 66 | + } catch (err) { |
| 67 | + CanceledError.rethrow(err, E_REASON_UNMOUNTED); //passthrough |
| 68 | + setText(`Failed: ${err}`); |
| 69 | + } |
| 70 | + |
| 71 | + return () => { |
| 72 | + console.log("unmount", this.isCanceled); |
| 73 | + }; |
| 74 | + }, [props.url]); |
| 75 | + |
| 76 | + //setTimeout(()=> cancel("Ooops!"), 1000); |
| 77 | + |
| 78 | + return <div>{text}</div>; |
| 79 | +} |
| 80 | +```` |
| 81 | +To learn more about available features, see the c-promise2 [documentation](https://www.npmjs.com/package/c-promise2). |
| 82 | + |
| 83 | +## Playground |
| 84 | + |
| 85 | +To get it, clone the repository and run `npm run playground` in the project directory or |
| 86 | +just use the codesandbox [demo](https://codesandbox.io/s/async-effect-demo1-vho29) to play with the library online. |
| 87 | + |
| 88 | +## Related projects |
| 89 | +- [c-promise2](https://www.npmjs.com/package/c-promise2) - promise with cancellation, decorators, timeouts, progress capturing, pause and user signals support |
| 90 | +- [cp-axios](https://www.npmjs.com/package/cp-axios) - a simple axios wrapper that provides an advanced cancellation api |
| 91 | +- [cp-fetch](https://www.npmjs.com/package/cp-fetch) - fetch with timeouts and request cancellation |
| 92 | + |
| 93 | +## License |
| 94 | + |
| 95 | +The MIT License Copyright (c) 2021 Dmitriy Mozgovoy robotshara@gmail.com |
| 96 | + |
| 97 | +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: |
| 98 | + |
| 99 | +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. |
| 100 | + |
| 101 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, |
| 102 | +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR |
| 103 | +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, |
| 104 | +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 105 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
0 commit comments