Skip to content

Commit

Permalink
feat: default dependency array for useAsync and useAsyncRetry
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 31, 2019
2 parents 94b4ea9 + e448d0d commit cb140a0
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 11 deletions.
6 changes: 4 additions & 2 deletions src/__stories__/useAsync.story.tsx
Expand Up @@ -10,13 +10,15 @@ const fn = () => new Promise<string>((resolve) => {
});

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

return (
<div>
{loading
? <div>Loading...</div>
: <div>Value: {value}</div>
: error
? <div>Error: {error.message}</div>
: <div>Value: {value}</div>
}
</div>
);
Expand Down
12 changes: 6 additions & 6 deletions src/__stories__/useAsyncRetry.story.tsx
Expand Up @@ -19,13 +19,13 @@ const DemoRetry = () => {

return (
<div>
{loading?
<div>Loading...</div>
: error?
<div>Error: {error.message}</div>
: <div>Value: {value}</div>
{loading
? <div>Loading...</div>
: error
? <div>Error: {error.message}</div>
: <div>Value: {value}</div>
}
<a href='javascript:void 0' onClick={() => retry()}>Retry</a>
<button onClick={() => retry()}>Retry</button>
</div>
);
};
Expand Down
2 changes: 1 addition & 1 deletion src/useAsync.ts
Expand Up @@ -17,7 +17,7 @@ export type AsyncState<T> =
value: T;
};

const useAsync = <T>(fn: () => Promise<T>, deps: DependencyList) => {
const useAsync = <T>(fn: () => Promise<T>, deps: DependencyList = []) => {
const [state, set] = useState<AsyncState<T>>({
loading: true
});
Expand Down
7 changes: 5 additions & 2 deletions src/useAsyncRetry.ts
Expand Up @@ -4,18 +4,21 @@ import useAsync, { AsyncState } from './useAsync';
export type AsyncStateRetry<T> = AsyncState<T> & {
retry():void
}
const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList) => {

const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList = []) => {
const [attempt, setAttempt] = useState<number>(0);
const state = useAsync(fn,[...deps, attempt]);
const state = useAsync(fn, [...deps, attempt]);

const stateLoading = state.loading;
const retry = useCallback(() => {
if (stateLoading) {
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]);

Expand Down

0 comments on commit cb140a0

Please sign in to comment.