Skip to content

Commit

Permalink
feat: new hook useAsync (#119)
Browse files Browse the repository at this point in the history
* feat: new hook `useAsync`

* test: tests for `useAsync` hook

* docs: docs for `useAsync` hook
  • Loading branch information
xobotyi authored Jun 14, 2021
1 parent 82032be commit 54bbc00
Show file tree
Hide file tree
Showing 7 changed files with 607 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ export { useSyncedRef } from './useSyncedRef/useSyncedRef';
export { useLocalStorageValue } from './useLocalStorageValue/useLocalStorageValue';
export { useSessionStorageValue } from './useSessionStorageValue/useSessionStorageValue';
export { useCookie, IUseCookieReturn } from './useCookie/useCookie';
export {
useAsync,
IAsyncState,
IAsyncStatus,
IUseAsyncActions,
IUseAsyncMeta,
IUseAsyncOptions,
} from './useAsync/useAsync';

// Sensor
export {
Expand Down
30 changes: 30 additions & 0 deletions src/useAsync/__docs__/example.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import * as React from 'react';
import { useAsync } from '../..';

export const Example: React.FC = () => {
const [state, actions] = useAsync(
() =>
new Promise<string>((resolve) => {
setTimeout(() => {
resolve('react-hookz is awesome!');
}, 3000);
}),
[]
);

return (
<div>
<div>
<em>Async function will resolve after 3 seconds of wait</em>
</div>
<br />
<div>promise status: {state.status}</div>
<div>current value: {state.result ?? 'undefined'}</div>
<br />
<div>
<button onClick={actions.reset}>reset</button>{' '}
<button onClick={actions.execute}>execute</button>
</div>
</div>
);
};
57 changes: 57 additions & 0 deletions src/useAsync/__docs__/story.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { Canvas, Meta, Story } from '@storybook/addon-docs/blocks';
import { Example } from './example.stories';

<Meta title="Side-effect/useAsync" component={Example} />

# useAsync

Executes provided async function and tracks its result and error.

- Handles any async functions.
- Safe - no worries about updating the state of unmounted component.
- Stable - returned methods do not change between renders.
- Handles race conditions - only latest results are stored in state.
- SSR-friendly, no requests performed on the server.
- Provides methods to manually trigger fetch.
- Options to customize behaviour.

#### Example

<Canvas>
<Story story={Example} inline />
</Canvas>

## Reference

```ts
export function useAsync<Result, Args extends unknown[] = unknown[]>(
asyncFn: (...params: Args) => Promise<Result>,
args: Args,
options?: IUseAsyncOptions<Result>
): [IAsyncState<Result>, IUseAsyncActions<Result, Args>, IUseAsyncMeta<Result, Args>];
```

#### Arguments

- **asyncFn** _`(...params: Args) => Promise<Result>`_ - Function that returns a promise.
- **args** _`Args`_ - Arguments list that will be passed to async function. Acts as dependencies
list for underlying `useEffect` hook.
- **options** - Hook options:
- **initialValue** _`Result`_ _(default: `undefined`)_ - Value that will be set on initialisation,
before the async function is executed.
- **skipMount** _`boolean`_ _(default: `false`)_ - Skip mount async function execution.
- **skipUpdate** _`boolean`_ _(default: `false`)_ - Skip update async function execution.

#### Return

0. **state**
- **status** _`'loading' | 'success' | 'error' | 'not-executed'`_ - latest promise status.
- **result** _`Result | undefined`_ - promise result if promise fulfilled.
- **error** _`Error | undefined`_ - promise error if promise rejected.
1. **methods**
- **reset** _`() => void`_- Reset state to initial, when async function haven't been executed.
- **execute** _`(...args: Args) => Promise<Result>`_- Execute async function manually.
2. **meta**
- **promise** _`Promise<Result> | undefined`_- Recent promise returned from async function.
- **lastArgs** _`Args | undefined`_ - List of arguments applied to recent async function
invocation.
Loading

0 comments on commit 54bbc00

Please sign in to comment.