mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
Merge pull request #186 from xiaoxiangmoe/master
fix: fix deps arg and union type in useAsync and useAsyncRetry
This commit is contained in:
commit
41fdcabd09
@ -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;
|
||||
|
||||
@ -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 };
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user