Merge pull request #79 from xiaoxiangmoe/master

feat: use discriminated union in useAsync
This commit is contained in:
Va Da 2018-12-17 15:00:24 +01:00 committed by GitHub
commit d9d23fd3a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 9 deletions

View File

@ -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>
);

View File

@ -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",

View File

@ -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>>({