react-promise-hooks
v1.0.5
Published
Lightweight hook package to handle promises
Downloads
9
Readme
react-promise-hooks
Lightweight hook package to handle promises
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