Back to Vueuse

useAsyncState

packages/core/useAsyncState/index.md

14.3.02.5 KB
Original Source

useAsyncState

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.

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)
  },
})