https://github.com/hanford/use-loadable
React hook for knowing when an async function is loading or had an error
https://github.com/hanford/use-loadable
async hooks loadable react use-loadable
Last synced: about 1 year ago
JSON representation
React hook for knowing when an async function is loading or had an error
- Host: GitHub
- URL: https://github.com/hanford/use-loadable
- Owner: hanford
- License: mit
- Created: 2018-10-29T04:52:37.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-01-11T21:11:04.000Z (over 7 years ago)
- Last Synced: 2024-12-02T21:13:21.519Z (over 1 year ago)
- Topics: async, hooks, loadable, react, use-loadable
- Language: JavaScript
- Size: 76.2 KB
- Stars: 9
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# `use-loadable`
> React hook for Loadable
> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`
## Install
```sh
yarn add use-loadable
```
## Usage
```js
import useLoadable from 'use-loadable'
const sleep = time => () => new Promise(done => setTimeout(done, time));
function App() {
const [{ loading, error, res }, onClick] = useLoadable(sleep(500));
return (
res: {JSON.stringify(res)}
error: {JSON.stringify(error)}
loading: {JSON.stringify(loading)}
{loading ? "Loading..." : "Load"}
);
}
```
### Using delayMs
Sometimes async functions will be cached and the function will return too quickly resulting in a flicker. To mitigate that, you can pass an optional `{ delayMs }` argument to `useLoadable`
```js
const sleep = () => new Promise(done => done());
function App() {
// this will take atleast 300ms to resolve
const [{ loading, error, res }, onClick] = useLoadable(sleep, { delayMs: 300 });
return (
{loading ? "Loading..." : "Load"}
);
}
```
[](https://codesandbox.io/s/ykv17px719)