use-cancelable
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

use-cancelable

React Hook for creating a cancelable promise to avoid state mutations after a component has unmounted.

Installation

Install by using npm i -S use-cancelable or yarn add use-cancelable

Usage

Import the hook import useCancelable from 'use-cancelable';

Then in your Functional React Component invoke the hook to acquire a wrapper function you can use on your promises

export default function Foo() {
  // hook
  const cancelable = useCancelable();


  const [loading, setLoading] = useState(false);
  useEffect(() => {
    setLoading(true);
    cancelable(makeAsyncRequest()).then(() => {
      // request has completed
      setLoading(false);
    })
  }, [])
  // ...
}

Note The cancelable Promise's finally method will run regardless of whether the promise was canceled. The cancelable method accepts an optional second parameter to provide a finally callback which is only inovoked if the promise resolves in an uncanceled state.

Note The cancelable method accepts an optional third parameter to make the promise reject when it resolves after cancelation. The rejection is passed a single object parameter so you can differentiate a cancelation rejection from other promise rejections:

{isCanceled: true}

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 2.0.1
    7
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 2.0.1
    7
  • 2.0.0
    1
  • 1.0.1
    1
  • 1.0.0
    1

Package Sidebar

Install

npm i use-cancelable

Weekly Downloads

10

Version

2.0.1

License

MIT

Unpacked Size

5.18 kB

Total Files

5

Last publish

Collaborators

  • foush0