Merge pull request #186 from xiaoxiangmoe/master

fix: fix deps arg and union type in useAsync and useAsyncRetry
This commit is contained in:
Va Da 2019-03-28 16:00:09 +01:00 committed by GitHub
commit 41fdcabd09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 15 deletions

View File

@ -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;

View File

@ -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 };
};