Skip to content

Commit

Permalink
fix: fix deps arg and union type in useAsync and useAsyncRetry
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaoxiangmoe committed Mar 28, 2019
1 parent 0a53a56 commit 929e726
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 15 deletions.
22 changes: 15 additions & 7 deletions src/useAsync.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, DependencyList } from 'react';

export interface AsyncState<T> {
loading: boolean;
error?: Error;
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 useAsync = <T>(fn: () => Promise<T>, deps: DependencyList) => {
const [state, set] = useState<AsyncState<T>>({
loading: true
});
const memoized = useCallback(fn, args);
const memoized = useCallback(fn, deps);

useEffect(() => {
let mounted = true;
Expand Down
19 changes: 11 additions & 8 deletions src/useAsyncRetry.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { useCallback, useState } from 'react';
import useAsync from './useAsync';
import { useCallback, useState, DependencyList } from 'react';
import useAsync, { AsyncState } from './useAsync';

const useAsyncRetry = <T>(fn: () => Promise<T>, args: any[] = []) => {
export type AsyncStateRetry<T> = AsyncState<T> & {
retry():void
}
const useAsyncRetry = <T>(fn: () => Promise<T>, deps: DependencyList) => {
const [attempt, setAttempt] = useState<number>(0);
const memoized = useCallback(() => fn(), [...args, attempt]);
const state = useAsync(memoized);
const state = useAsync(fn,[...deps, attempt]);

const stateLoading = state.loading;
const retry = useCallback(() => {
if (state.loading) {
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 + 1);
}, [memoized, state, attempt]);
setAttempt(attempt => attempt + 1);
}, [...deps, stateLoading, attempt]);

return { ...state, retry };
};
Expand Down

0 comments on commit 929e726

Please sign in to comment.