From 2c49244537d543980ab37e78283e4f351a2d9c88 Mon Sep 17 00:00:00 2001 From: Ward Oosterlijnck Date: Sun, 31 Mar 2019 13:03:14 +1100 Subject: [PATCH 1/2] Default dependency array for useAsync and useAsyncRetry --- src/useAsync.ts | 2 +- src/useAsyncRetry.ts | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/useAsync.ts b/src/useAsync.ts index c648c69197..83521bf79a 100644 --- a/src/useAsync.ts +++ b/src/useAsync.ts @@ -17,7 +17,7 @@ export type AsyncState = value: T; }; -const useAsync = (fn: () => Promise, deps: DependencyList) => { +const useAsync = (fn: () => Promise, deps: DependencyList = []) => { const [state, set] = useState>({ loading: true }); diff --git a/src/useAsyncRetry.ts b/src/useAsyncRetry.ts index 80be726e98..6e7053ff91 100644 --- a/src/useAsyncRetry.ts +++ b/src/useAsyncRetry.ts @@ -4,9 +4,10 @@ import useAsync, { AsyncState } from './useAsync'; export type AsyncStateRetry = AsyncState & { retry():void } -const useAsyncRetry = (fn: () => Promise, deps: DependencyList) => { + +const useAsyncRetry = (fn: () => Promise, deps: DependencyList = []) => { const [attempt, setAttempt] = useState(0); - const state = useAsync(fn,[...deps, attempt]); + const state = useAsync(fn, [...deps, attempt]); const stateLoading = state.loading; const retry = useCallback(() => { @@ -14,8 +15,10 @@ const useAsyncRetry = (fn: () => Promise, deps: DependencyList) => { if (process.env.NODE_ENV === 'development') { console.log('You are calling useAsyncRetry hook retry() method while loading in progress, this is a no-op.'); } + return; } + setAttempt(attempt => attempt + 1); }, [...deps, stateLoading, attempt]); From e448d0d4f7f3bd99ff5440930ce78d69874aa7b1 Mon Sep 17 00:00:00 2001 From: Ward Oosterlijnck Date: Sun, 31 Mar 2019 13:06:31 +1100 Subject: [PATCH 2/2] Align useAsync and useAsyncRetry demos --- src/__stories__/useAsync.story.tsx | 6 ++++-- src/__stories__/useAsyncRetry.story.tsx | 12 ++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/__stories__/useAsync.story.tsx b/src/__stories__/useAsync.story.tsx index 84ed0eaff4..ee68514dce 100644 --- a/src/__stories__/useAsync.story.tsx +++ b/src/__stories__/useAsync.story.tsx @@ -10,13 +10,15 @@ const fn = () => new Promise((resolve) => { }); const Demo = () => { - const {loading, value} = useAsync(fn); + const {loading, error, value} = useAsync(fn); return (
{loading ?
Loading...
- :
Value: {value}
+ : error + ?
Error: {error.message}
+ :
Value: {value}
}
); diff --git a/src/__stories__/useAsyncRetry.story.tsx b/src/__stories__/useAsyncRetry.story.tsx index 38b2985724..c6248b02e0 100644 --- a/src/__stories__/useAsyncRetry.story.tsx +++ b/src/__stories__/useAsyncRetry.story.tsx @@ -19,13 +19,13 @@ const DemoRetry = () => { return (
- {loading? -
Loading...
- : error? -
Error: {error.message}
- :
Value: {value}
+ {loading + ?
Loading...
+ : error + ?
Error: {error.message}
+ :
Value: {value}
} - retry()}>Retry +
); };