Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useAsyncState.md
1---2category: State3---45# useAsyncState67Reactive async state. Will not block your setup function and will trigger changes once the promise is ready. The state is a `shallowRef` by default.89## Usage1011```ts12import { useAsyncState } from '@vueuse/core'13import axios from 'axios'1415const { state, isReady, isLoading, error } = useAsyncState(16axios17.get('https://jsonplaceholder.typicode.com/todos/1')18.then(t => t.data),19{ id: null },20)21```2223### Return Values2425| Property | Description |26| ------------------ | --------------------------------------------------- |27| `state` | The result of the async function |28| `isReady` | `true` when the promise has resolved at least once |29| `isLoading` | `true` while the promise is pending |30| `error` | The error if the promise was rejected |31| `execute` | Re-execute the async function with optional delay |32| `executeImmediate` | Re-execute immediately (shorthand for `execute(0)`) |3334### Awaiting the Result3536The return value is thenable, so you can await it in async functions or `<script setup>`:3738```ts39const { state, isReady } = await useAsyncState(fetchData, null)40// `state` is now populated, `isReady` is true41```4243### Manual Execution4445Set `immediate: false` to prevent automatic execution on creation.4647```vue48<script setup lang="ts">49import { useAsyncState } from '@vueuse/core'5051const { state, execute, executeImmediate } = useAsyncState(action, '', { immediate: false })5253async function action(event) {54await new Promise(resolve => setTimeout(resolve, 500))55return `${event.target.textContent} clicked!`56}57</script>5859<template>60<p>State: {{ state }}</p>6162<button class="button" @click="executeImmediate">63Execute now64</button>6566<button class="ml-2 button" @click="event => execute(500, event)">67Execute with delay68</button>69</template>70```7172### Options7374```ts75const { state } = useAsyncState(promise, initialState, {76// Execute immediately on creation (default: true)77immediate: true,78// Delay before first execution in ms (default: 0)79delay: 0,80// Reset state to initial before each execution (default: true)81resetOnExecute: true,82// Use shallowRef for state (default: true)83shallow: true,84// Throw errors instead of catching them (default: false)85throwError: false,86// Called when promise resolves87onSuccess(data) {88console.log('Success:', data)89},90// Called when promise rejects91onError(error) {92console.error('Error:', error)93},94})95```9697## Type Declarations9899```ts100export interface UseAsyncStateReturnBase<101Data,102Params extends any[],103Shallow extends boolean,104> {105state: Shallow extends true ? Ref<Data> : Ref<UnwrapRef<Data>>106isReady: Ref<boolean>107isLoading: Ref<boolean>108error: Ref<unknown>109execute: (delay?: number, ...args: Params) => Promise<Data | undefined>110executeImmediate: (...args: Params) => Promise<Data | undefined>111}112export type UseAsyncStateReturn<113Data,114Params extends any[],115Shallow extends boolean,116> = UseAsyncStateReturnBase<Data, Params, Shallow> &117PromiseLike<UseAsyncStateReturnBase<Data, Params, Shallow>>118export interface UseAsyncStateOptions<Shallow extends boolean, D = any> {119/**120* Delay for the first execution of the promise when "immediate" is true. In milliseconds.121*122* @default 0123*/124delay?: number125/**126* Execute the promise right after the function is invoked.127* Will apply the delay if any.128*129* When set to false, you will need to execute it manually.130*131* @default true132*/133immediate?: boolean134/**135* Callback when error is caught.136*/137onError?: (e: unknown) => void138/**139* Callback when success is caught.140* @param {D} data141*/142onSuccess?: (data: D) => void143/**144* Sets the state to initialState before executing the promise.145*146* This can be useful when calling the execute function more than once (for147* example, to refresh data). When set to false, the current state remains148* unchanged until the promise resolves.149*150* @default true151*/152resetOnExecute?: boolean153/**154* Use shallowRef.155*156* @default true157*/158shallow?: Shallow159/**160*161* An error is thrown when executing the execute function162*163* @default false164*/165throwError?: boolean166}167/**168* Reactive async state. Will not block your setup function and will trigger changes once169* the promise is ready.170*171* @see https://vueuse.org/useAsyncState172* @param promise The promise / async function to be resolved173* @param initialState The initial state, used until the first evaluation finishes174* @param options175*/176export declare function useAsyncState<177Data,178Params extends any[] = any[],179Shallow extends boolean = true,180>(181promise: Promise<Data> | ((...args: Params) => Promise<Data>),182initialState: MaybeRef<Data>,183options?: UseAsyncStateOptions<Shallow, Data>,184): UseAsyncStateReturn<Data, Params, Shallow>185```186