Async state: one value, not three refs
Splitting async loads across separate loading, error, and data refs invites contradictory UI states—and uncancelled async watchers let slow older responses overwrite newer selections (vue-async-race).
In short
- One state value: use
useTaskfrom@evobug_com/safe-ts-vue/taskto hold oneAsyncState<T, E>(Idle,Loading,Ready,Failed). - Automatic cancellation: every new
run(...)aborts the previousAbortSignal, and unmount cancels in-flight work. - Exhaustive templates: render every state variant with
<Match>, compiled into a zero-costv-ifchain.
In the examples below, fetchUser(id, signal) returns Promise<Result<User, ApiError>>:
✕ Rejectedvue-async-racevue-split-state
vue
<script setup lang="ts">
import { ref, watch } from "vue";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fetchUser, type User } from "./api";
const props = defineProps<{ id: string }>();
const loading = ref(false);
const failed = ref("");
const user = ref<User>();
watch(() => props.id, async (id) => {
loading.value = true;
const result = await fetchUser(id);
loading.value = false;
if (isErr(result)) failed.value = result.error.message;
else user.value = result;
}, { immediate: true });
</script>
<template>
<p v-if="loading">Loading…</p>
<p v-else-if="failed !== ''">{{ failed }}</p>
<p v-else-if="user">{{ user.name }}</p>
</template>useTask runs the work and keeps where it stands in one AsyncState value: Idle, Loading, Ready with a value, or Failed with an error. Each run(...) aborts the previous one, so only the latest response is shown, and the task is aborted when the component unmounts. <Match> shows the value, one slot per variant:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { watch } from "vue";
import { Match } from "@evobug_com/safe-ts-vue/match";
import { useTask } from "@evobug_com/safe-ts-vue/task";
import { fetchUser } from "./api";
const props = defineProps<{ id: string }>();
const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
watch(() => props.id, (id) => run(id), { immediate: true });
</script>
<template>
<Match :value="state">
<template #Loading>Loading…</template>
<template #Ready="{ value }">{{ value.name }}</template>
<template #Failed="{ error }">Couldn't load the user: {{ error.message }}</template>
<template #_></template>
</Match>
</template>A slot gets its variant's fields: in #Ready="{ value }", value is the User, never undefined. #_ shows every variant without a slot of its own (here Idle), and goes last.
Started in setup, before the template exists. watch(..., { immediate: true }) runs the first run during setup, before the template has rendered: the component's template refs (useElement) are still null then. The task's function must not read one before its first await. Read it after the await (and check it, with useOptionalElement: the component may be gone by then), or start the first run in onMounted. The same holds for a load function you pass to another component, which may start it in its own setup. vue-template-ref reports a function that reads a useElement before its first await and is started during setup, by an immediate watcher, or passed to a component as a prop.
<Match> works like match(...) in the script. The checker finds the variants of the value's type, from how it is declared (useTask, ref<Payment>(...), defineProps<{ payment: Payment }>(), a function's return type) and the Enum<...> declaration, here or in the file it is imported from. A variant without a slot, or a slot that isn't a variant, is reported (vue-match):
✕ Rejectedvue-match
vue
<script setup lang="ts">
import { Match } from "@evobug_com/safe-ts-vue/match";
import { useTask } from "@evobug_com/safe-ts-vue/task";
import { fetchUser } from "./api";
const props = defineProps<{ id: string }>();
const { state } = useTask((signal) => fetchUser(props.id, signal));
</script>
<template>
<Match :value="state">
<template #Loading>Loading…</template>
<template #Ready="{ value }">{{ value.name }}</template>
</Match>
</template>A failed load would show nothing, and so would an idle task. When someone adds a variant to an enum, every <Match> without a slot for it is reported: a list of places to update, as with match.
Unlike match(...), <Match> doesn't take a value that may be missing (an Option of the enum) yet: there is no #undefined slot. Put it under v-if="value", with v-else for the missing case.
The build turns <Match> into a v-if chain on .tag, with the slot props replaced by reads of the value (value.name becomes state.value.name). Nothing is left of it at runtime. Where it can't (a value that isn't a plain name like a.b, slot props with defaults), the Match component renders the same thing; so does a test that mounts the component without the build.
Pass the value, not a Ref. The template only unwraps refs at the top level, so const task = useTask(...) needs :value="task.state.value". Destructured, as above, state is a top-level ref and :value="state" works. The checker tells you when .value is missing.
A v-if chain on .tag is checked the same way (vue-exhaustive-v-if). A chain that misses a variant is reported, whatever the variant is called:
✕ Rejectedvue-exhaustive-v-if
vue
<script setup lang="ts">
import { watch } from "vue";
import { useTask } from "@evobug_com/safe-ts-vue/task";
import { fetchUser } from "./api";
const props = defineProps<{ id: string }>();
const user = useTask((signal, id: string) => fetchUser(id, signal));
const state = user.state;
watch(() => props.id, (id) => user.run(id), { immediate: true });
</script>
<template>
<p v-if="state.tag === 'Loading'">Loading…</p>
<p v-else-if="state.tag === 'Ready'">{{ state.value.name }}</p>
</template>(state is a ref, which the template unwraps: state.value there is the value field of Ready.) Ending the chain with v-else makes it pass, but a variant added later then lands in the v-else without anyone being told. <Match> with a slot per variant is told.
The same chain reads well with is from @evobug_com/safe-ts-std/enum, which narrows the value inside its block as the .tag test does, and is checked the same way. It takes a variant's name (is(state, 'Ready')) or its constructor. For a generic enum such as AsyncState<T, E> there is no constructors<...>() table of your own: use the one exported next to the type, AsyncState from @evobug_com/safe-ts-vue. A project that reads enums one way only turns on prefer-is-over-tag, which reports the .tag form in templates too.
✅ Also accepted: a chain of is that names every variant, when the branches are different elements and you'd rather not nest them in <Match>
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { watch } from "vue";
import { is } from "@evobug_com/safe-ts-std/enum";
import { AsyncState, useTask } from "@evobug_com/safe-ts-vue";
import { fetchUser } from "./api";
const props = defineProps<{ id: string }>();
const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
watch(() => props.id, (id) => run(id), { immediate: true });
</script>
<template>
<p v-if="is(state, AsyncState.Idle)"></p>
<p v-else-if="is(state, AsyncState.Loading)">Loading…</p>
<p v-else-if="is(state, AsyncState.Ready)">{{ state.value.name }}</p>
<p v-else-if="is(state, AsyncState.Failed)">Couldn't load the user: {{ state.error.message }}</p>
</template>One difference with vue-tsc (3.3): inside an event handler (@click="open(row.path)") of a v-else-if or v-else branch under v-for, the row narrowed by is is never, where a .tag test keeps it narrowed. The same code in a function of the script compiles. Give such a branch its own v-if="is(row, Row.File)" instead of v-else-if.
When every variant shows the same element, compute what it shows with match instead:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { computed, watch } from "vue";
import { match } from "@evobug_com/safe-ts-std/enum";
import { useTask } from "@evobug_com/safe-ts-vue/task";
import { fetchUser } from "./api";
const props = defineProps<{ id: string }>();
const user = useTask((signal, id: string) => fetchUser(id, signal));
watch(() => props.id, (id) => user.run(id), { immediate: true });
const status = computed(() =>
match(user.state.value, {
Idle: () => "",
Loading: () => "Loading…",
Ready: ({ value }) => value.name,
Failed: ({ error }) => `Couldn't load the user: ${error.message}`,
}),
);
</script>
<template>
<p>{{ status }}</p>
</template>Starting over, and a task that throws
abort() stops the run in progress and puts state back to Idle. Once a run is over it does nothing: Ready or Failed stays. To forget the outcome (a "dismiss" button, another item selected whose answer must not show the old one), call reset(), which aborts a run in progress too.
A run that throws or rejects instead of returning an Err is a bug: the failures you expect belong in the Result. It doesn't become Failed, whose error is your E. state goes back to Idle, the promise run(...) returned rejects (Vue passes it to app.config.errorHandler from a handler, a hook or a watch), and panic holds what was thrown, as a std Panic, until the next run or reset(). A template with nothing for Idle then shows a blank where the crash was, so give Idle something to say:
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { watch } from "vue";
import { Match } from "@evobug_com/safe-ts-vue/match";
import { useTask } from "@evobug_com/safe-ts-vue/task";
import { fetchUser } from "./api";
const props = defineProps<{ id: string }>();
const { state, panic, run, reset } = useTask((signal, id: string) => fetchUser(id, signal));
watch(() => props.id, (id) => run(id), { immediate: true });
</script>
<template>
<Match :value="state">
<template #Idle>
<p v-if="panic">Something went wrong. <button @click="run(props.id)">Try again</button></p>
</template>
<template #Loading>Loading…</template>
<template #Ready="{ value }">{{ value.name }} <button @click="reset()">Close</button></template>
<template #Failed="{ error }">Couldn't load the user: {{ error.message }}</template>
</Match>
</template>The three refs of the first example are reported on their own too (vue-split-state): a loading ref turned on before an await and off after it, next to other refs set after it. So is a ref() without a value that is filled after an await and shown in the template (vue-ref-without-value): until it's loaded, the template has to cope with undefined, and failure has nowhere to go.
A component loaded with defineAsyncComponent can fail to load too (the network, a new deploy). Give it an errorComponent (vue-async-component).
Tasks in a store
A task needs an effect scope, not a component. A Pinia setup store runs its function in one, so useTask works there as it does in setup: the store keeps only the newest run's answer, every run aborts the previous run's signal, and the task is aborted when the store's scope ends (store.$dispose(), or the app unmounting). Expose its state and run:
ts
import { defineStore } from "pinia";
import { useTask } from "@evobug_com/safe-ts-vue/task";
import { fetchTeam } from "./api";
export const useTeamStore = defineStore("team", () => {
const team = useTask((signal, id: string) => fetchTeam(id, signal));
return { team: team.state, ask: team.run };
});A store that keeps a counter for the same job (let latestAsk = 0, bumped before the await, compared after it) throws away an older answer but lets its request run on. With the idiomatic rules on, latest-wins-counter reports it, and unused-task-signal a task that never passes its signal on to a request that could take it. Whether or not the idiomatic rules are on, superseded-task-write reports a task's callback that changes state itself after an await without asking its signal: return the value instead, and read it from state.
Rules on this page: vue-async-race, vue-match, vue-exhaustive-v-if, vue-split-state, vue-ref-without-value, vue-async-component