Skip to content

computedAsync

Category
Export Size
382 B
Last Changed
2 months ago
Alias
asyncComputed

Computed for async functions.

Demo

Evaluating: false
userId: 1
id: 1
title: delectus aut autem
completed: false

Usage

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
name
=
shallowRef
('jack')
const
userInfo
=
computedAsync
(
async () => { return await mockLookUp(
name
.
value
)
}, null, // initial state )
js
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const name = shallowRef('jack')
const userInfo = computedAsync(async () => {
  return await mockLookUp(name.value)
}, null)

Evaluation State

Pass a ref to track if the async function is currently evaluating.

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
evaluating
=
shallowRef
(false)
const
userInfo
=
computedAsync
(
async () => { /* your logic */ }, null,
evaluating
, // can also be passed via options: { evaluating }
)
js
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const evaluating = shallowRef(false)
const userInfo = computedAsync(
  async () => {
    /* your logic */
  },
  null,
  evaluating,
)

onCancel

When 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.

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
packageName
=
shallowRef
('@vueuse/core')
const
downloads
=
computedAsync
(async (
onCancel
) => {
const
abortController
= new
AbortController
()
onCancel
(() =>
abortController
.
abort
())
return await
fetch
(
`https://api.npmjs.org/downloads/point/last-week/${
packageName
.
value
}`,
{
signal
:
abortController
.
signal
},
) .
then
(
response
=>
response
.
ok
?
response
.
json
() : {
downloads
: '' })
.
then
(
result
=>
result
.downloads)
}, 0)

Lazy

By default, computedAsync will start resolving immediately on creation. Specify lazy: true to make it start resolving on the first access.

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
evaluating
=
shallowRef
(false)
const
userInfo
=
computedAsync
(
async () => { /* your logic */ }, null, {
lazy
: true,
evaluating
},
)

Error Handling

Use the onError callback to handle errors from the async function.

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
name
=
shallowRef
('jack')
const
userInfo
=
computedAsync
(
async () => { return await mockLookUp(
name
.
value
)
}, null, {
onError
(
e
) {
console
.
error
('Failed to fetch user info',
e
)
}, }, )

Shallow Ref

By default, computedAsync uses shallowRef internally. Set shallow: false to use a deep ref instead.

ts
import { 
computedAsync
} from '@vueuse/core'
import {
shallowRef
} from 'vue'
const
name
=
shallowRef
('jack')
const
userInfo
=
computedAsync
(
async () => { return await fetchNestedData(
name
.
value
)
}, null, {
shallow
: false }, // enables deep reactivity
)
js
import { computedAsync } from '@vueuse/core'
import { shallowRef } from 'vue'
const name = shallowRef('jack')
const userInfo = computedAsync(
  async () => {
    return await fetchNestedData(name.value)
  },
  null,
  { shallow: false },
)

Caveats

  • 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.

  • 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.

Type Declarations

Show Type Declarations
ts
/**
 * Handle overlapping async evaluations.
 *
 * @param cancelCallback The provided callback is invoked when a re-evaluation of the computed value is triggered before the previous one finished
 */
export type 
AsyncComputedOnCancel
= (
cancelCallback
:
Fn
) => void
export interface
AsyncComputedOptions
<
Lazy
= boolean,
> extends ConfigurableFlushSync { /** * Should value be evaluated lazily * * @default false */
lazy
?:
Lazy
/** * Ref passed to receive the updated of async evaluation */
evaluating
?:
Ref
<boolean>
/** * Use shallowRef * * @default true */
shallow
?: boolean
/** * Callback when error is caught. */
onError
?: (
e
: unknown) => void
} /** * Create an asynchronous computed dependency. * * @see https://vueuse.org/computedAsync * @param evaluationCallback The promise-returning callback which generates the computed value * @param initialState The initial state, used until the first evaluation finishes * @param optionsOrRef Additional options or a ref passed to receive the updates of the async evaluation */ export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
:
T
,
optionsOrRef
:
AsyncComputedOptions
<true>,
):
ComputedRef
<
T
>
export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
: undefined,
optionsOrRef
:
AsyncComputedOptions
<true>,
):
ComputedRef
<
T
| undefined>
export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
:
T
,
optionsOrRef
?:
Ref
<boolean> |
AsyncComputedOptions
,
):
Ref
<
T
>
export declare function
computedAsync
<
T
>(
evaluationCallback
: (
onCancel
:
AsyncComputedOnCancel
) =>
T
|
Promise
<
T
>,
initialState
?: undefined,
optionsOrRef
?:
Ref
<boolean> |
AsyncComputedOptions
,
):
Ref
<
T
| undefined>
/** @deprecated use `computedAsync` instead */ export declare const
asyncComputed
: typeof
computedAsync

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
Fernando Fernández
Vida Xie
xiankaiqun
Arthur Darkstone
bab
Yu Lia
SerKo
IlyaL
OrbisK
Icey Wu
sun0day
Yugang Cao
Bodo Graumann

Changelog

v14.0.0-alpha.2 on
e5f74 - feat!: deprecate alias exports in favor of original function names (#5009)
v14.0.0-alpha.1 on
573bf - feat!: default to flush: sync (#4752)
v13.7.0 on
226a2 - feat: use globalThis.reportError as default onError (#4943)
v13.3.0 on
217cc - fix(asyncComputed): fix types for AsyncComputedOptions
v13.2.0 on
b1718 - fix: return ComputedRef type when lazy: true (#4751)
b1bc8 - feat: add option to control watcher's flush timing (#4746)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v11.1.0 on
45b18 - fix: type signature (#4207)

Released under the MIT License.

The new era of AI engineering.
Workflows, artifacts, and judgment that scale.
Request Early Access