@mariosant/react-async-hooks
v0.5.1
Published
> Tame that async beast right with the power of React Hooks!
Downloads
2
Readme
Async Hooks for React
Tame that async beast right with the power of React Hooks!
Installation
Add @mariosant/react-async-hooks
to your package.json
.
$ npm install @mariosant/react-async-hooks
# or
$ yarn add @mariosant/react-async-hooks
You can now import the module and use it like
import {useAsync, useAsyncTrigger} from '@mariosant/react-async-hooks';
Usage
The module consists of two different hooks, useAsync
and useAsyncTrigger
. The reason for that is, this way you can easily pick when the hook is going to be executed.
useAsync
useAsync(fn, deps)
will execute the provided async function as soon as the component renders.
import {useAsync} from '@mariosant/react-async-hooks';
const fetchAsyncFn = async () => {
// do something async
};
const Component = props => {
const [{pending, data, error}, {reload}] = useAsync(fetchAsyncFn, []);
return <div>...</div>;
};
useAsyncTrigger
useAsyncTrigger(fn)
is very similar to useAsync
, but instead the action will be invoked imperitevely.
import {useAsyncTrigger} from '@mariosant/react-async-hooks';
const fetchAsyncFn = async () => {
// do something async
};
const Component = props => {
const [{pending, data, error}, {trigger] = useAsyncTrigger(fetchAsyncFn);
return (
<div>
...
<button onClick={trigger}>Click me</button>
...
</div>
);
};
Meta
Marios Antonoudiou – @marios_ant – [email protected]
Distributed under the MIT license.
https://github.com/mariosant/react-async-hooks
Contributing
- Fork it (https://github.com/mariosant/react-async-hooks/fork)
- Create your feature branch (
git checkout -b feature/fooBar
) - Commit your changes using a semantic commit message.
- Push to the branch (
git push origin feature/fooBar
) - Create a new Pull Request