From 966af4aaee360b743d95b7e174aec4aae3bd4d5b Mon Sep 17 00:00:00 2001 From: ZHAO Jinxiang Date: Mon, 17 Dec 2018 21:12:38 +0800 Subject: [PATCH] feat: use discriminated union in useAsync --- docs/useAsync.md | 10 ++++++---- package.json | 2 +- src/useAsync.ts | 16 ++++++++++++---- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/docs/useAsync.md b/docs/useAsync.md index 4757cc9350..bb5d071e40 100644 --- a/docs/useAsync.md +++ b/docs/useAsync.md @@ -17,13 +17,15 @@ const fn = () => new Promise((resolve) => { }); const Demo = () => { - const {loading, value, error} = useAsync(fn); + const state = useAsync(fn); return (
- {loading - ?
Loading...
- :
Value: {value}
+ {state.loading? +
Loading...
+ : state.error? +
Error...
+ :
Value: {state.value}
}
); diff --git a/package.json b/package.json index 477294be71..3d24e6c3e3 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/useAsync.ts b/src/useAsync.ts index c18df27314..aa0ecfe180 100644 --- a/src/useAsync.ts +++ b/src/useAsync.ts @@ -1,10 +1,18 @@ import {useState, useEffect, useCallback} from 'react'; -export interface AsyncState { - loading: boolean; - error?: Error | any; - value?: T; +export type AsyncState = +| { + loading: true; } +| { + loading: false; + error: Error; +} +| { + loading: false; + error?: undefined; + value: T; +}; const useAsync = (fn: () => Promise, args?) => { const [state, set] = useState>({