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/computedAsync.md
1---2category: Reactivity3alias: asyncComputed4---56# computedAsync78Computed for async functions.910## Usage1112```ts13import { computedAsync } from '@vueuse/core'14import { shallowRef } from 'vue'1516const name = shallowRef('jack')1718const userInfo = computedAsync(19async () => {20return await mockLookUp(name.value)21},22null, // initial state23)24```2526### Evaluation State2728Pass a ref to track if the async function is currently evaluating.2930```ts31import { computedAsync } from '@vueuse/core'32import { shallowRef } from 'vue'3334const evaluating = shallowRef(false)3536const userInfo = computedAsync(37async () => { /* your logic */ },38null,39evaluating, // can also be passed via options: { evaluating }40)41```4243### onCancel4445When the computed source changes before the previous async function resolves, you may want to cancel the previous one. Here is an example showing how to incorporate with the fetch API.4647```ts48import { computedAsync } from '@vueuse/core'49import { shallowRef } from 'vue'5051const packageName = shallowRef('@vueuse/core')5253const downloads = computedAsync(async (onCancel) => {54const abortController = new AbortController()5556onCancel(() => abortController.abort())5758return await fetch(59`https://api.npmjs.org/downloads/point/last-week/${packageName.value}`,60{ signal: abortController.signal },61)62.then(response => response.ok ? response.json() : { downloads: '—' })63.then(result => result.downloads)64}, 0)65```6667### Lazy6869By default, `computedAsync` will start resolving immediately on creation. Specify `lazy: true` to make it start resolving on the first access.7071```ts72import { computedAsync } from '@vueuse/core'73import { shallowRef } from 'vue'7475const evaluating = shallowRef(false)7677const userInfo = computedAsync(78async () => { /* your logic */ },79null,80{ lazy: true, evaluating },81)82```8384### Error Handling8586Use the `onError` callback to handle errors from the async function.8788```ts89import { computedAsync } from '@vueuse/core'90import { shallowRef } from 'vue'9192const name = shallowRef('jack')9394const userInfo = computedAsync(95async () => {96return await mockLookUp(name.value)97},98null,99{100onError(e) {101console.error('Failed to fetch user info', e)102},103},104)105```106107### Shallow Ref108109By default, `computedAsync` uses `shallowRef` internally. Set `shallow: false` to use a deep ref instead.110111```ts112import { computedAsync } from '@vueuse/core'113import { shallowRef } from 'vue'114115const name = shallowRef('jack')116117const userInfo = computedAsync(118async () => {119return await fetchNestedData(name.value)120},121null,122{ shallow: false }, // enables deep reactivity123)124```125126## Caveats127128- Just like Vue's built-in `computed` function, `computedAsync` does dependency tracking and is automatically re-evaluated when dependencies change. Note however that only dependencies referenced in the first call stack are considered for this. In other words: **Dependencies that are accessed asynchronously will not trigger re-evaluation of the async computed value.**129130- As opposed to Vue's built-in `computed` function, re-evaluation of the async computed value is triggered whenever dependencies are changing, regardless of whether its result is currently being tracked or not.131132## Type Declarations133134```ts135/**136* Handle overlapping async evaluations.137*138* @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished139*/140export type AsyncComputedOnCancel = (cancelCallback: Fn) => void141export interface AsyncComputedOptions<142Lazy = boolean,143> extends ConfigurableFlushSync {144/**145* Should value be evaluated lazily146*147* @default false148*/149lazy?: Lazy150/**151* Ref passed to receive the updated of async evaluation152*/153evaluating?: Ref<boolean>154/**155* Use shallowRef156*157* @default true158*/159shallow?: boolean160/**161* Callback when error is caught.162*/163onError?: (e: unknown) => void164}165/**166* Create an asynchronous computed dependency.167*168* @see https://vueuse.org/computedAsync169* @param evaluationCallback The promise-returning callback which generates the computed value170* @param initialState The initial state, used until the first evaluation finishes171* @param optionsOrRef Additional options or a ref passed to receive the updates of the async evaluation172*/173export declare function computedAsync<T>(174evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,175initialState: T,176optionsOrRef: AsyncComputedOptions<true>,177): ComputedRef<T>178export declare function computedAsync<T>(179evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,180initialState: undefined,181optionsOrRef: AsyncComputedOptions<true>,182): ComputedRef<T | undefined>183export declare function computedAsync<T>(184evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,185initialState: T,186optionsOrRef?: Ref<boolean> | AsyncComputedOptions,187): Ref<T>188export declare function computedAsync<T>(189evaluationCallback: (onCancel: AsyncComputedOnCancel) => T | Promise<T>,190initialState?: undefined,191optionsOrRef?: Ref<boolean> | AsyncComputedOptions,192): Ref<T | undefined>193/** @deprecated use `computedAsync` instead */194export declare const asyncComputed: typeof computedAsync195```196