mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Merge pull request #79 from xiaoxiangmoe/master
feat: use discriminated union in useAsync
This commit is contained in:
commit
d9d23fd3a6
@ -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>
|
||||
);
|
||||
|
||||
@ -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",
|
||||
|
||||
@ -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>>({
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user