Skip to content

Commit

Permalink
docs: docs for useAsync hook
Browse files Browse the repository at this point in the history
  • Loading branch information
xobotyi committed Jun 13, 2021
1 parent 0c86e8d commit bd51a92
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/useAsync/__docs__/example.stories.tsx
@@ -1,4 +1,30 @@
import * as React from 'react';
import { useAsync } from '../..';

export const Example: React.FC = () => null;
export const Example: React.FC = () => {
const [state, actions] = useAsync(
() =>
new Promise((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>
);
};
45 changes: 45 additions & 0 deletions src/useAsync/__docs__/story.mdx
Expand Up @@ -5,8 +5,53 @@ import { Example } from './example.stories';

# 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.
16 changes: 16 additions & 0 deletions src/useAsync/__tests__/dom.ts
Expand Up @@ -321,4 +321,20 @@ describe('useAsync', () => {
});
});
});

it('should not change methods between renders', () => {
const spy = jest.fn(async () => {});
const { rerender, result } = renderHook(() =>
useAsync(spy, [], {
skipUpdate: true,
skipMount: true,
})
);

const res1 = result.current;
rerender();

expect(res1[1].execute).toBe(result.current[1].execute);
expect(res1[1].reset).toBe(result.current[1].reset);
});
});
6 changes: 6 additions & 0 deletions src/useAsync/useAsync.ts
Expand Up @@ -55,7 +55,13 @@ export interface IUseAsyncActions<Result, Args extends unknown[] = unknown[]> {
}

export interface IUseAsyncMeta<Result, Args extends unknown[] = unknown[]> {
/**
* Recent promise returned from async function.
*/
promise: Promise<Result> | undefined;
/**
* List of arguments applied to recent async function invocation.
*/
lastArgs: Args | undefined;
}

Expand Down
10 changes: 10 additions & 0 deletions utility/add-new-hook.js
Expand Up @@ -59,6 +59,16 @@ import { Example } from './example.stories';
<Canvas>
<Story story={Example} inline />
</Canvas>
## Reference
\`\`\`ts
\`\`\`
#### Arguments
#### Return
`
);

Expand Down

0 comments on commit bd51a92

Please sign in to comment.