Skip to content

Commit e38e8d9

Browse files
authored
feat(useAsyncState): allow initial value to be a ref (#4992)
1 parent ba71846 commit e38e8d9

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

packages/core/useAsyncState/index.test.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { promiseTimeout } from '@vueuse/shared'
22
import { describe, expect, it, vi } from 'vitest'
3-
import { nextTick } from 'vue'
3+
import { nextTick, shallowRef } from 'vue'
44
import { useAsyncState } from './index'
55

66
describe('useAsyncState', () => {
@@ -110,4 +110,13 @@ describe('useAsyncState', () => {
110110
expect(mockReportError).toHaveBeenCalledWith(error)
111111
globalThis.reportError = originalReportError
112112
})
113+
114+
it('supports initialState as shallow ref', async () => {
115+
const initialState = shallowRef(200)
116+
const asyncValue = Promise.resolve(100)
117+
const { state } = useAsyncState(asyncValue, initialState)
118+
await asyncValue
119+
expect(state.value).toBe(100)
120+
expect(initialState).toBe(state)
121+
})
113122
})

packages/core/useAsyncState/index.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import type { Ref, ShallowRef, UnwrapRef } from 'vue'
1+
import type { MaybeRef, Ref, ShallowRef, UnwrapRef } from 'vue'
22
import { noop, promiseTimeout, until } from '@vueuse/shared'
3-
import { ref as deepRef, shallowRef } from 'vue'
3+
import { ref as deepRef, shallowRef, toValue } from 'vue'
44

55
export interface UseAsyncStateReturnBase<Data, Params extends any[], Shallow extends boolean> {
66
state: Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>
@@ -81,7 +81,7 @@ export interface UseAsyncStateOptions<Shallow extends boolean, D = any> {
8181
*/
8282
export function useAsyncState<Data, Params extends any[] = any[], Shallow extends boolean = true>(
8383
promise: Promise<Data> | ((...args: Params) => Promise<Data>),
84-
initialState: Data,
84+
initialState: MaybeRef<Data>,
8585
options?: UseAsyncStateOptions<Shallow, Data>,
8686
): UseAsyncStateReturn<Data, Params, Shallow> {
8787
const {
@@ -100,7 +100,7 @@ export function useAsyncState<Data, Params extends any[] = any[], Shallow extend
100100

101101
async function execute(delay = 0, ...args: any[]) {
102102
if (resetOnExecute)
103-
state.value = initialState
103+
state.value = toValue(initialState)
104104
error.value = undefined
105105
isReady.value = false
106106
isLoading.value = true

0 commit comments

Comments
 (0)