Skip to content

useAsyncState

Category
Export Size
974 B
Last Changed
2 months ago

Reactive async state. Will not block your setup function and will trigger changes once the promise is ready. The state is a shallowRef by default.

Demo

Ready: false
Loading: true
{}

Usage

ts
import { 
useAsyncState
} from '@vueuse/core'
import
axios
from 'axios'
const {
state
,
isReady
,
isLoading
,
error
} =
useAsyncState
(
axios
.
get
('https://jsonplaceholder.typicode.com/todos/1')
.
then
(
t
=>
t
.
data
),
{
id
: null },
)

Return Values

PropertyDescription
stateThe result of the async function
isReadytrue when the promise has resolved at least once
isLoadingtrue while the promise is pending
errorThe error if the promise was rejected
executeRe-execute the async function with optional delay
executeImmediateRe-execute immediately (shorthand for execute(0))

Awaiting the Result

The return value is thenable, so you can await it in async functions or <script setup>:

ts
const { 
state
,
isReady
} = await useAsyncState(fetchData, null)
// `state` is now populated, `isReady` is true

Manual Execution

Set immediate: false to prevent automatic execution on creation.

vue
<script setup lang="ts">
import { 
useAsyncState
} from '@vueuse/core'
const {
state
,
execute
,
executeImmediate
} =
useAsyncState
(
action
, '', {
immediate
: false })
async function
action
(
event
) {
await new
Promise
(
resolve
=>
setTimeout
(
resolve
, 500))
return `${
event
.target.textContent} clicked!`
} </script> <template> <
p
>State: {{
state
}}</
p
>
<
button
class
="button" @
click
="
executeImmediate
">
Execute now </
button
>
<
button
class
="ml-2 button" @
click
="
event
=>
execute
(500,
event
)">
Execute with delay </
button
>
</template>

Options

ts
const { 
state
} = useAsyncState(promise, initialState, {
// Execute immediately on creation (default: true)
immediate
: true,
// Delay before first execution in ms (default: 0)
delay
: 0,
// Reset state to initial before each execution (default: true)
resetOnExecute
: true,
// Use shallowRef for state (default: true)
shallow
: true,
// Throw errors instead of catching them (default: false)
throwError
: false,
// Called when promise resolves
onSuccess
(
data
) {
console
.
log
('Success:',
data
)
}, // Called when promise rejects
onError
(
error
) {
console
.
error
('Error:',
error
)
}, })

Type Declarations

Show Type Declarations
ts
export interface 
UseAsyncStateReturnBase
<
Data
,
Params
extends any[],
Shallow
extends boolean,
> {
state
:
Shallow
extends true ?
Ref
<
Data
> :
Ref
<
UnwrapRef
<
Data
>>
isReady
:
Ref
<boolean>
isLoading
:
Ref
<boolean>
error
:
Ref
<unknown>
execute
: (
delay
?: number, ...
args
:
Params
) =>
Promise
<
Data
| undefined>
executeImmediate
: (...
args
:
Params
) =>
Promise
<
Data
| undefined>
} export type
UseAsyncStateReturn
<
Data
,
Params
extends any[],
Shallow
extends boolean,
> =
UseAsyncStateReturnBase
<
Data
,
Params
,
Shallow
> &
PromiseLike
<
UseAsyncStateReturnBase
<
Data
,
Params
,
Shallow
>>
export interface
UseAsyncStateOptions
<
Shallow
extends boolean,
D
= any> {
/** * Delay for the first execution of the promise when "immediate" is true. In milliseconds. * * @default 0 */
delay
?: number
/** * Execute the promise right after the function is invoked. * Will apply the delay if any. * * When set to false, you will need to execute it manually. * * @default true */
immediate
?: boolean
/** * Callback when error is caught. */
onError
?: (
e
: unknown) => void
/** * Callback when success is caught. * @param {D} data */
onSuccess
?: (
data
:
D
) => void
/** * Sets the state to initialState before executing the promise. * * This can be useful when calling the execute function more than once (for * example, to refresh data). When set to false, the current state remains * unchanged until the promise resolves. * * @default true */
resetOnExecute
?: boolean
/** * Use shallowRef. * * @default true */
shallow
?:
Shallow
/** * * An error is thrown when executing the execute function * * @default false */
throwError
?: boolean
} /** * Reactive async state. Will not block your setup function and will trigger changes once * the promise is ready. * * @see https://vueuse.org/useAsyncState * @param promise The promise / async function to be resolved * @param initialState The initial state, used until the first evaluation finishes * @param options */ export declare function
useAsyncState
<
Data
,
Params
extends any[] = any[],
Shallow
extends boolean = true,
>(
promise
:
Promise
<
Data
> | ((...
args
:
Params
) =>
Promise
<
Data
>),
initialState
:
MaybeRef
<
Data
>,
options
?:
UseAsyncStateOptions
<
Shallow
,
Data
>,
):
UseAsyncStateReturn
<
Data
,
Params
,
Shallow
>

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
丶远方
James Garbutt
Flamenco
machete
Vida Xie
Andrew Kazakov
Jialong Lu
duyifei
David Gonzalez
Robin
Robin
Joris Gallot
Jules Raffoux
hfutsora
Brain777777
Mao Mr
Jelf
Sergey Shumov
lsdsjy
IIFelix
Alex Francev
webfansplz
Shinigami
Shahar Kosti
Alex Kozack
ordago
Jacob Clevenger
Antério Vieira

Changelog

v14.2.0 on
0c346 - fix: ensure execute return the actual data (#5167)
v14.0.0-beta.1 on
3e6cb - fix: track latest execution to avoid newer results being replaced by outdated ones (#5047)
v14.0.0-alpha.0 on
e38e8 - feat: allow initial value to be a ref (#4992)
v13.7.0 on
f6e88 - feat!: set globalThis.reportError as default onError (#4951)
v13.4.0 on
82740 - feat: add executeImmediate with the same type as the promise fn (#4716)
v12.1.0 on
4d0a7 - fix: use ShallowRef instead of Ref type (#4294)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)

Released under the MIT License.

FREE Weekend
Unlimited access to Mid-Level JavaScript training
Incl. 18 Coding Challenges + Trial Exam
Reserve Your Spot
43
hours
:
16
minutes
:
06
seconds
: