useAction
useAction
<script setup lang="ts">
import { greet } from '#safe-action/actions'
const name = ref('')
const { execute, executeAsync, data, serverError, validationErrors, isExecuting, cancel, reset } =
useAction(greet, {
timeout: 10_000,
onSuccess({ data, input }) { console.log(data.greeting) },
onError({ error, input }) { console.error(error) },
})
</script>
<template>
<form @submit.prevent="execute({ name })">
<label for="name">Name</label>
<input id="name" v-model="name" />
<p v-for="message in validationErrors?.name" :key="message">{{ message }}</p>
<p v-if="serverError" role="alert">{{ serverError }}</p>
<button :disabled="isExecuting">Greet</button>
<button type="button" @click="cancel()">Cancel request</button>
<button type="button" @click="reset()">Reset result</button>
<p v-if="data">{{ data.greeting }}</p>
</form>
</template>
Awaiting a result
execute(input) starts the action and returns void. executeAsync(input) resolves the full ActionResult; it does not unwrap data or throw for an ordinary action/transport error.
const result = await executeAsync({ name: 'Ada' })
if (result.serverError !== undefined) {
console.error(result.serverError)
} else if (result.validationErrors !== undefined) {
console.error(result.validationErrors)
} else {
console.log(result.data?.greeting)
}
A successful void action can return {} over HTTP and still has status hasSucceeded. Test error properties rather than data truthiness. data retains the last success during subsequent executions or errors; call reset() to clear it.
Concurrent requests and callbacks
The latest-started execution owns reactive state. Older completions cannot overwrite it or run onSuccess, onError, or onSettled. Every call's promise resolves its own result. onExecute runs for every start. Set cancelPrevious: true to abort older owned requests when starting another.
Callbacks receive the existing object shapes: { input }, { data, input }, { error, input }, and { result, input }. They are notifications, not awaited continuations. Callback exceptions/rejections are logged and cannot convert a completed action into an error or produce double settlement. Await executeAsync() for work whose completion your own code depends on.
Cancellation and lifecycle
cancel() invalidates pending state updates, aborts owned requests, and sets status to idle. It preserves already-stored data and errors. reset() also clears those values. Cancelled calls resolve an error envelope; callbacks are suppressed for explicit cancellation/reset because those executions no longer own state.
A run that has already delivered onSuccess or onError finishes its lifecycle even if that callback calls reset() or starts another execution: its invalidate refresh still runs and onSettled still fires. Only the reactive state is released. This makes onSuccess() { reset() } safe with invalidate.
signal accepts an external AbortSignal. timeout aborts a request after the positive number of milliseconds specified. These failures become the latest error result when you have not explicitly invalidated the execution. Cancellation does not undo a mutation that already reached the server.
By default, neither component disposal nor SPA navigation cancels owned requests. Opt into scope cancellation with abortOnDispose: true when calling the composable inside component setup. detached: true selects native browser fetch instead of Nuxt $fetch. It does not provide a stronger delivery guarantee; page unload, closed tabs, networking, or server failure can still interrupt work. Native fetch requires browser-relative URL resolution, so use the default transport for server execution.
Request configuration
useAction(greet, {
headers: () => ({ 'X-Request-Source': 'profile' }),
credentials: 'same-origin',
signal: controller.signal,
timeout: 10_000,
cancelPrevious: true,
abortOnDispose: true,
})
The module disables automatic fetch retries to avoid silently repeating mutations. If you implement application retries, design idempotency first. All options and returned values.