Vue demo: one component, two ways
Compare the same profile loader built two ways, running live in your browser against a simulated server (Ada responds in 2 s, Grace in 0.4 s, and Linus fails). On the left: the typical loading / error / person refs plus an async watcher. On the right: SAFE-TS with useTask and <Match>.
In short
- Try Linus first: the plain component crashes rendering
person.name; SAFE-TS renders#Failed. - Try Ada, then Grace quickly: Ada's late response overwrites Grace on the left;
useTaskaborts Ada on the right. - Try Grace → Linus → Grace: stale errors stick on the left;
AsyncStateholds only one state at a time on the right.
Pick someone above to start a request.
Pick someone above to start a request.
Try this
Press Start over between tries.
- Pick Linus first. On the left, the component crashes:
personis still undefined, andperson.namethrows while rendering. In an app, Vue shows nothing in its place. On the right, you see the error. - Pick Ada, then Grace before Ada has loaded. On the left, Grace appears, then two seconds later Ada replaces her while Grace is still selected: the slower, older response arrived last. On the right, picking Grace aborted Ada's request, and Grace stays.
- Pick Grace, then Linus, then Grace again. On the left, Linus's error shows on top of Grace's details, and when you pick Grace again it stays, because nothing clears it. On the right, each pick shows only its own outcome.
If you test the left version by picking someone and waiting, all of this works. That is why code like it ships.
Without SAFE-TS
vue
<script setup lang="ts">
import { ref, watch } from "vue";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fetchPerson, type Person } from "./api";
const props = defineProps<{ id: string }>();
const loading = ref(false);
const error = ref("");
const person = ref<Person>();
watch(() => props.id, async (id) => {
loading.value = true;
const result = await fetchPerson(id);
loading.value = false;
if (isErr(result)) error.value = result.error.message;
else person.value = result;
}, { immediate: true });
</script>
<template>
<p v-if="loading">Loading…</p>
<article v-else>
<p v-if="error !== ''" class="error">{{ error }}</p>
<h3>{{ person.name }}</h3>
<p>{{ person.role }}</p>
</article>
</template>- Line 13,
vue-split-state: `loading`, `error`, `person` are one async state kept in separate refs and set one by one around `await`: they can disagree (an error next to the previous data, an older request ending the newer one's `loading`) - Line 15,
vue-async-race: This watcher writes state after `await` without cancelling the previous run: when the source changes quickly, an older, slower response overwrites the newer one - Line 25,
vue-maybe-undefined: `person` may be undefined (`ref()` without a value): reading `.name` from it then throws, and the component doesn't render - Line 26,
vue-maybe-undefined: `person` may be undefined (`ref()` without a value): reading `.role` from it then throws, and the component doesn't render
Each report is one of the tries:
vue-maybe-undefined, try 1.ref<Person>()starts asundefined, and the template assumes that once it's not loading, there is a person. A template isn't type-checked unless you runvue-tsc, so this compiles.vue-async-race, try 2. Each change ofidstarts another run of the watcher, and nothing stops the previous one. The response that arrives last wins, whichever request it answers.vue-split-state, try 3. One async state is kept in three refs, set one at a time, and they can disagree:errorfrom one request next topersonfrom another. (It also coversvue-ref-without-value, which reports a ref likepersonwhen it's on its own.)
Fixing it by hand
All three can be fixed without SAFE-TS: clear error and person at the start, ignore a run that a newer one replaced, and check person before reading it:
✕ Rejectedvue-split-state
vue
<script setup lang="ts">
import { ref, watch } from "vue";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fetchPerson, type Person } from "./api";
const props = defineProps<{ id: string }>();
const loading = ref(false);
const error = ref("");
const person = ref<Person>();
watch(() => props.id, async (id, _old, onCleanup) => {
let replaced = false;
onCleanup(() => {
replaced = true;
});
loading.value = true;
error.value = "";
person.value = undefined;
const result = await fetchPerson(id);
if (replaced) return;
loading.value = false;
if (isErr(result)) error.value = result.error.message;
else person.value = result;
}, { immediate: true });
</script>
<template>
<p v-if="loading">Loading…</p>
<p v-else-if="error !== ''" class="error">{{ error }}</p>
<article v-else-if="person">
<h3>{{ person.name }}</h3>
<p>{{ person.role }}</p>
</article>
</template>That works, and every component that loads something has to repeat it without forgetting a step. The requests it ignores still run to the end, and the three refs still have to be kept in step by hand. That is why vue-split-state still reports it.
With SAFE-TS
✓ 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 { fetchPerson } from "./api";
const props = defineProps<{ id: string }>();
const { state, run } = useTask((signal, id: string) => fetchPerson(id, signal));
watch(() => props.id, (id) => run(id), { immediate: true });
</script>
<template>
<Match :value="state">
<template #Loading><p>Loading…</p></template>
<template #Ready="{ value }">
<article>
<h3>{{ value.name }}</h3>
<p>{{ value.role }}</p>
</article>
</template>
<template #Failed="{ error }"><p class="error">{{ error.message }}</p></template>
<template #Idle></template>
</Match>
</template>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 { fetchPerson } from "./api";
const props = defineProps<{ id: string }>();
const { state, run } = useTask((signal, id: string) => fetchPerson(id, signal));
watch(() => props.id, (id) => run(id), { immediate: true });
</script>
<template>
<template v-if="state.tag === 'Loading'"><p>Loading…</p></template>
<template v-else-if="state.tag === 'Ready'">
<article>
<h3>{{ state.value.name }}</h3>
<p>{{ state.value.role }}</p>
</article>
</template>
<template v-else-if="state.tag === 'Failed'"><p class="error">{{ state.error.message }}</p></template>
<template v-else-if="state.tag === 'Idle'"></template>
</template>useTaskkeeps where the load stands in oneAsyncStatevalue:Idle,Loading,Readywith avalue, orFailedwith anerror. It can't be two of them at once, so there is no error next to someone else's data, and nothing to clear (try 3).- Each
run(id)aborts the previous run: itssignalfires, and the fake server stops waiting. Only the latest run can changestate(try 2). When the component unmounts, the run in progress is aborted too. <Match>has a slot per variant. In#Ready="{ value }",valueis thePerson, neverundefined(try 1), andFailedhas its own slot. The checker makes sure every variant has one (vue-match). Take out#Failed, and it is reported before anything runs:
✕ Rejectedvue-match
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 { fetchPerson } from "./api";
const props = defineProps<{ id: string }>();
const { state, run } = useTask((signal, id: string) => fetchPerson(id, signal));
watch(() => props.id, (id) => run(id), { immediate: true });
</script>
<template>
<Match :value="state">
<template #Loading><p>Loading…</p></template>
<template #Ready="{ value }"><h3>{{ value.name }}</h3></template>
<template #Idle></template>
</Match>
</template>The Compiled tab above shows what the build makes of the component: <Match> becomes a v-if chain on state.tag, and value.name becomes state.value.name. That is the code running in the demo, so <Match> costs nothing at runtime.
Side by side
| What you saw | Without SAFE-TS | With SAFE-TS |
|---|---|---|
| The panel crashes on a failed first load | person.name with person undefined: vue-maybe-undefined | value exists only in #Ready |
| An older response replaces a newer one | an async watcher nothing cancels: vue-async-race | run aborts the previous run |
| An error next to someone else's details, and it never clears | three refs that can disagree: vue-split-state | one AsyncState, one variant at a time |
| A state the template forgot | not reported; that state shows nothing | vue-match |
The demo's files are in docs/.vitepress/theme/demo/: api.ts is the fake server, and the code above is generated from the files that run, so it can't drift from them. To set up a project of your own, see Vue: Setup. The repository also has a small working app in examples/vue/.