Skip to content

doasync/use-promise

Repository files navigation

React usePromise hook

NPM Version NPM Downloads GitHub issues Telegram

An optimized hook for handling promises in React

It supports promise.cache property (or function), which is used by some libraries and prevents unnecessary rerenders. You can use it too if you want

Installation

npm install use-promise

or

yarn add use-promise

Usage

Wrap a promise in usePromise hook and you will get back the following array: [result, error, pending]. Use array destructuring to get values that you need:

  const [company] = usePromise(fetchCompanyPromise)
  const [users, usersError, usersLoading] = usePromise(fetchUsersPromise)

Do not call an async function inside usePromise to get a promise! You will need already prepared promise for this hook. If you don't have a promise, but you want to get it from an async call, then use useAsyncCall from use-call package:

const [user, userError, userLoading] = useAsyncCall(fetchUser, 120)

useAsyncCall hook uses usePromise from this package to get promise state

Tip

If you found this hook useful, please star this package on GitHub

Author

@doasync

About

usePromise React hook

Resources

License

Stars

Watchers

Forks

Packages

No packages published