From 929e72679b5e74b6752ffb8c4a7417a9ff0468a7 Mon Sep 17 00:00:00 2001 From: ZHAO Jinxiang Date: Thu, 28 Mar 2019 22:32:35 +0800 Subject: [PATCH] fix: fix deps arg and union type in useAsync and useAsyncRetry --- src/useAsync.ts | 22 +++++++++++++++------- src/useAsyncRetry.ts | 19 +++++++++++-------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/src/useAsync.ts b/src/useAsync.ts index 8749baec..509f9991 100644 --- a/src/useAsync.ts +++ b/src/useAsync.ts @@ -1,16 +1,24 @@ -import { useState, useEffect, useCallback } from 'react'; +import { useState, useEffect, useCallback, DependencyList } from 'react'; -export interface AsyncState { - loading: boolean; - error?: Error; - value?: T; +export type AsyncState = +| { + loading: true; +} +| { + loading: false; + error: Error; +} +| { + loading: false; + error?: undefined; + value: T; }; -const useAsync = (fn: () => Promise, args?) => { +const useAsync = (fn: () => Promise, deps: DependencyList) => { const [state, set] = useState>({ loading: true }); - const memoized = useCallback(fn, args); + const memoized = useCallback(fn, deps); useEffect(() => { let mounted = true; diff --git a/src/useAsyncRetry.ts b/src/useAsyncRetry.ts index 0382df24..80be726e 100644 --- a/src/useAsyncRetry.ts +++ b/src/useAsyncRetry.ts @@ -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 = (fn: () => Promise, args: any[] = []) => { +export type AsyncStateRetry = AsyncState & { + retry():void +} +const useAsyncRetry = (fn: () => Promise, deps: DependencyList) => { const [attempt, setAttempt] = useState(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 }; };