Skip to content

Commit

Permalink
feat: use discriminated union in useAsync
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoxiangmoe committed Dec 17, 2018
1 parent 8d3dbd4 commit 966af4a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
10 changes: 6 additions & 4 deletions docs/useAsync.md
Expand Up @@ -17,13 +17,15 @@ const fn = () => new Promise((resolve) => {
});

const Demo = () => {
const {loading, value, error} = useAsync(fn);
const state = useAsync(fn);

return (
<div>
{loading
? <div>Loading...</div>
: <div>Value: {value}</div>
{state.loading?
<div>Loading...</div>
: state.error?
<div>Error...</div>
: <div>Value: {state.value}</div>
}
</div>
);
Expand Down
2 changes: 1 addition & 1 deletion package.json
Expand Up @@ -43,7 +43,7 @@
"@storybook/react": "^3.4.11",
"react": "next",
"react-dom": "next",
"typescript": "^3.1.3",
"typescript": "^3.2.2",
"ts-node": "^7.0.1",
"ts-loader": "3",
"babel-core": "^6.26.3",
Expand Down
16 changes: 12 additions & 4 deletions src/useAsync.ts
@@ -1,10 +1,18 @@
import {useState, useEffect, useCallback} from 'react';

export interface AsyncState<T> {
loading: boolean;
error?: Error | any;
value?: T;
export type AsyncState<T> =
| {
loading: true;
}
| {
loading: false;
error: Error;
}
| {
loading: false;
error?: undefined;
value: T;
};

const useAsync = <T>(fn: () => Promise<T>, args?) => {
const [state, set] = useState<AsyncState<T>>({
Expand Down

0 comments on commit 966af4a

Please sign in to comment.