1.3.0 • Published 4 years ago

react-hooks-useasync v1.3.0

Weekly downloads
2
License
MIT
Repository
github
Last release
4 years ago

useAsync

npm

License: MIT

npm bundle size

A React hook for wrapping async operations

Find it on npm

Or just add it to your project with npm i --save react-hooks-useasync

How to use

The package exposes a single method, useAsync, which takes 1-2 arguments and returns a tuple of three arguments:

const [value, state, wrappedMethod] = useAsync(
  originalMethod,
  (defaultValue = undefined)
);

Thanks to TypeScript shenanigans, wrappedMethod will have the same named and typed parameters as originalMethod and value will have the return type of originalMethod (with undefined added if no defaultValue has been specified)

state is defined via an export enum AsyncState, with the four possible values idle (method has yet to be called), pending (method has been called but it hasn't resolved yet), done (method has finished with a result), or error (method has encountered an error, and the raw error is now in the value variable).

useAsync will detect when a caller unmounts, and will avoid attempting to update the state

A Code Sandbox example

1.3.0

4 years ago

1.2.0

4 years ago

1.1.0

4 years ago

1.0.0

5 years ago