Skip to content

Commit

Permalink
docs: improve useAsync demo and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Jul 16, 2019
2 parents 18b7c99 + f1c0987 commit 446806c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 21 deletions.
16 changes: 5 additions & 11 deletions docs/useAsync.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,16 @@
React hook that resolves an `async` function or a function that returns
a promise;


## Usage

```jsx
import {useAsync} from 'react-use';

// Returns a Promise that resolves after one second.
const fn = () => new Promise((resolve) => {
setTimeout(() => {
resolve('RESOLVED');
}, 1000);
});

const Demo = () => {
const state = useAsync(fn);
const Demo = ({delay = 1000}) => {
const state = useAsync(() => {
// Returns a Promise that resolves after x milliseconds
return new Promise((resolve) => setTimeout(() => resolve('RESOLVED'), delay);
}, [delay]);

return (
<div>
Expand All @@ -32,7 +27,6 @@ const Demo = () => {
};
```

## Reference
```ts
Expand Down
24 changes: 14 additions & 10 deletions src/__stories__/useAsync.story.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
import { number, withKnobs } from '@storybook/addon-knobs';
import { storiesOf } from '@storybook/react';
import * as React from 'react';
import { useAsync } from '..';
import ShowDocs from './util/ShowDocs';

const fn = () =>
new Promise<string>(resolve => {
setTimeout(() => {
resolve('RESOLVED');
}, 1000);
});

const Demo = () => {
const { loading, error, value } = useAsync<string>(fn);
const Demo = ({ delay }) => {
const { loading, error, value } = useAsync<string>(
() =>
new Promise<string>(resolve => {
setTimeout(() => resolve('RESOLVED'), delay);
}),
[delay]
);

return (
<div>{loading ? <div>Loading...</div> : error ? <div>Error: {error.message}</div> : <div>Value: {value}</div>}</div>
);
};

storiesOf('Side effects|useAsync', module)
.addDecorator(withKnobs)
.add('Docs', () => <ShowDocs md={require('../../docs/useAsync.md')} />)
.add('Demo', () => <Demo />);
.add('Demo', () => {
const delay = number('delay', 1000, { range: true, min: 100, max: 5000, step: 100 });
return <Demo delay={delay} />;
});

0 comments on commit 446806c

Please sign in to comment.