Skip to content

Commit

Permalink
fix(useAsyncState): improve types (#1119)
Browse files Browse the repository at this point in the history
Co-authored-by: Anthony Fu <anthonyfu117@hotmail.com>
  • Loading branch information
macheteHot and antfu committed Jan 5, 2022
1 parent 503b4ec commit 247cc73
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions packages/core/useAsyncState/index.ts
@@ -1,16 +1,16 @@
import { noop, promiseTimeout } from '@vueuse/shared'
import type { Ref } from 'vue-demi'
import type { Ref, ShallowRef } from 'vue-demi'
import { ref, shallowRef } from 'vue-demi'

export interface UseAsyncStateReturn<T> {
state: Ref<T>
export interface UseAsyncStateReturn<Data, Shallow extends boolean> {
state: Shallow extends true ? ShallowRef<Data> : Ref<Data>
isReady: Ref<boolean>
isLoading: Ref<boolean>
error: Ref<unknown>
execute: (delay?: number, ...args: any[]) => Promise<T>
execute: (delay?: number, ...args: any[]) => Promise<Data>
}

export interface AsyncStateOptions {
export interface AsyncStateOptions<Shallow extends boolean> {
/**
* Delay for executing the promise. In milliseconds.
*
Expand Down Expand Up @@ -49,7 +49,7 @@ export interface AsyncStateOptions {
*
* @default true
*/
shallow?: boolean
shallow?: Shallow
}

/**
Expand All @@ -61,20 +61,20 @@ export interface AsyncStateOptions {
* @param initialState The initial state, used until the first evaluation finishes
* @param options
*/
export function useAsyncState<T>(
promise: Promise<T> | ((...args: any[]) => Promise<T>),
initialState: T,
options: AsyncStateOptions = {},
): UseAsyncStateReturn<T> {
export function useAsyncState<Data, Shallow extends boolean = true>(
promise: Promise<Data> | ((...args: any[]) => Promise<Data>),
initialState: Data,
options?: AsyncStateOptions<Shallow>,
): UseAsyncStateReturn<Data, Shallow> {
const {
immediate = true,
delay = 0,
onError = noop,
resetOnExecute = true,
shallow = true,
} = options
} = options ?? {}

const state = shallow ? shallowRef(initialState) : ref(initialState) as Ref<T>
const state = shallow ? shallowRef(initialState) : ref(initialState)
const isReady = ref(false)
const isLoading = ref(false)
const error = ref<unknown | undefined>(undefined)
Expand Down Expand Up @@ -105,14 +105,14 @@ export function useAsyncState<T>(
}

isLoading.value = false
return state.value
return state.value as Data
}

if (immediate)
execute(delay)

return {
state,
state: state as Shallow extends true ? ShallowRef<Data> : Ref<Data>,
isReady,
isLoading,
error,
Expand Down

0 comments on commit 247cc73

Please sign in to comment.