Skip to content

Commit

Permalink
Fix Promise type detection;
Browse files Browse the repository at this point in the history
Fix function name;
  • Loading branch information
xobotyi committed Sep 4, 2019
1 parent 641a879 commit 563f71d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
3 changes: 2 additions & 1 deletion src/useAsync.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { DependencyList, useEffect } from 'react';
import useAsyncFn, { FnReturningPromise } from './useAsyncFn';
import useAsyncFn from './useAsyncFn';
import { FnReturningPromise } from './util';

export { AsyncState, AsyncFnReturn } from './useAsyncFn';

Expand Down
12 changes: 7 additions & 5 deletions src/useAsyncFn.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { DependencyList, useCallback, useState } from 'react';
import useMountedState from './useMountedState';
import { FnReturningPromise, PromiseType } from './util';

export type AsyncState<T> =
| {
Expand All @@ -18,16 +19,17 @@ export type AsyncState<T> =
value: T;
};

export type FnReturningPromise = (...args: any[]) => Promise<any>;
export type AsyncFnReturn<T extends FnReturningPromise = FnReturningPromise> = [AsyncState<ReturnType<T>>, T];
type StateFromFnReturningPromise<T extends FnReturningPromise> = AsyncState<PromiseType<ReturnType<T>>>;

export default function useAsync<T extends FnReturningPromise>(
export type AsyncFnReturn<T extends FnReturningPromise = FnReturningPromise> = [StateFromFnReturningPromise<T>, T];

export default function useAsyncFn<T extends FnReturningPromise>(
fn: T,
deps: DependencyList = [],
initialState: AsyncState<ReturnType<T>> = { loading: false }
initialState: StateFromFnReturningPromise<T> = { loading: false }
): AsyncFnReturn<T> {
const isMounted = useMountedState();
const [state, set] = useState<AsyncState<ReturnType<T>>>(initialState);
const [state, set] = useState<StateFromFnReturningPromise<T>>(initialState);

const callback = useCallback((...args: Parameters<T>): ReturnType<T> => {
set({ loading: true });
Expand Down
4 changes: 4 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ export const isClient = typeof window === 'object';
export const on = (obj: any, ...args: any[]) => obj.addEventListener(...args);

export const off = (obj: any, ...args: any[]) => obj.removeEventListener(...args);

export type FnReturningPromise = (...args: any[]) => Promise<any>;

export type PromiseType<P extends Promise<any>> = P extends Promise<infer T> ? T : never;

0 comments on commit 563f71d

Please sign in to comment.