1.0.5 • Published 4 years ago

react-promise-hooks v1.0.5

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

react-promise-hooks

Lightweight hook package to handle promises

NPM JavaScript Style Guide

Install

npm i react-promise-hooks

Usage

usePromise()

  • Invoked on render of component
const { data, error, loading, refetch } = usePromise(PromiseFunction)
// or if you're using typescript
const [promiseRequest, { data, error, loading, done }] = usePromise<ReturnType, ParamType>(PromiseRequest)

useLazyPromise()

  • Invoked when promiseRequest function is called
const [promiseRequest, { data, error, loading, done }] = useLazyPromise(PromiseRequest)
// or if you're using typescript
const [promiseRequest, { data, error, loading, done }] = useLazyPromise<ReturnType, ParamType>(PromiseRequest)

Example Component

const PromiseRequest = (): Promise<Todo> => {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then((response) => response.json())
}

const App = () => {
  const { data, error, loading, refetch } = usePromise<Todo>(PromiseRequest)
  const [promiseRequest, results] = useLazyPromise<void, Todo>(PromiseRequest)

  return (
    <div>
      <h3>usePromise()</h3>
      <p>
        {JSON.stringify(data)} {error.occurred} {loading}
      </p>
      <button onClick={refetch}>Invoke Refetch for usePromise</button>
      <h3>useLazyPromise()</h3>
      <p>
        {JSON.stringify(results.data)} {error.occurred} {loading}
      </p>
      <button onClick={promiseRequest}>Invoke Lazy Promise</button>
    </div>
  )
}

License

MIT © crofoot

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago

0.0.1

4 years ago