Skip to content

@zwire/vue

Vue 3.5+ composables for @zwire/core: read-through refs, v-model atoms, optimistic mutations, incremental lists, async resources and SSR hydration.

Values always read through to signal.get() (snapshots are never copied or deeply proxied), and subscriptions are released by Vue’s effect scope, including after SSR.

Terminal window
npm install @zwire/core @zwire/vue
Entry Mirrors Exports
@zwire/vue @zwire/core ScopeProvider, provideScope, ScopeKey, useScope, useScoped, useSignal, useAtom, useSelector
@zwire/vue/tx @zwire/core/tx useOptimisticLayer, useOptimisticAction, useDraft
@zwire/vue/collections @zwire/core/collections useCollectionTopK, useCollectionRange, useCollectionItem, useCollectionSize
@zwire/vue/resource @zwire/core/resource useResource
@zwire/vue/protocol @zwire/core/protocol useHydrate, HydrationBoundary

Every composable takes an optional options object as its last argument; { scope } overrides the provided scope. Composables must run inside setup() or an effect scope and throw otherwise, because a ref created elsewhere could never update.

<script setup lang="ts">
import { atom } from '@zwire/core';
import { useAtom, useSelector, useSignal } from '@zwire/vue';
const count = atom(0);
const title = atom('');
const value = useSignal(count); // Readonly<Ref<number>>
const parity = useSelector(count, (n) => n % 2); // ComputedRef<number>
const model = useAtom(title); // Ref<string>, works with v-model
</script>
<template>
<input v-model="model" />
<button @click="count.set((n) => n + 1)">{{ value }} ({{ parity }})</button>
</template>
// state/account.ts: a definition at module level, instantiated once per scope
import { scoped } from '@zwire/core';
import { createQueryCollection } from '@zwire/core/collections';
import { hydratable } from '@zwire/core/protocol';
import { resource } from '@zwire/core/resource';
export const account = scoped((scope) => ({
balance: hydratable('balance', 0, { scope }),
orders: createQueryCollection<Order, number>({
scope,
getId: (order) => order.id,
compare: (a, b) => b.qty - a.qty,
}),
profile: resource((signal) => api.profile({ signal }), { scope, lazy: true }),
}));
App.vue
<script setup lang="ts">
import { ScopeProvider } from '@zwire/vue';
</script>
<template>
<!-- Without a `scope` prop the provider creates a scope and disposes it on unmount. -->
<ScopeProvider><Balance /></ScopeProvider>
</template>
Balance.vue
<script setup lang="ts">
import { useScoped, useSignal } from '@zwire/vue';
const { balance } = useScoped(account); // the instance for the provided scope
const available = useSignal(balance);
</script>
<template><output>{{ available }}</output></template>

Atoms belong to the scope they were created in. scoped() keeps the definition at module level and builds one instance per scope on first use, so a ScopeProvider (or a server request) gets its own state. Outside components, call the definition directly: account(scope).balance.set(1000). provideScope() does the same as the component from inside setup() and returns the scope; app.provide(ScopeKey, scope) provides one app-wide.

<script setup lang="ts">
import { useScoped } from '@zwire/vue';
import { useOptimisticAction } from '@zwire/vue/tx';
const { balance } = useScoped(account);
// One layer per call: reverted if the request fails, settled with the server's answer.
const reserve = useOptimisticAction(
async (tx, amount: number) => {
tx.update(balance, (b) => b - amount);
return api.reserve(amount, { signal: tx.signal });
},
{ settle: (result) => balance.set(result.balance) },
);
const { pending, error } = reserve; // refs
</script>
<template>
<button :disabled="pending" @click="reserve.run(150)">Reserve 150</button>
<p v-if="error" role="alert">Could not reserve</p>
</template>
  • run(...args) never throws; a failure lands in error. runAsync(...args) returns the promise.
  • Calls made while one is in flight run as parallel layers that rebase in order. Pass concurrency: 'latest' to abort the earlier call or 'drop' to ignore the new one.
  • A call keeps running if the component unmounts, so the server’s answer still lands. Pass abortOnUnmount: true to abort instead.

For a layer the UI holds open itself, useOptimisticLayer() returns { active, update, settle, revert }: the first update opens the layer, settle(serverUpdate?) or revert() closes it, and unmounting reverts it. useDraft() gives the same kind of handle for an STM draft (open, get, set, commit, discard); draft.get(signal) is reactive in templates.

<script setup lang="ts">
import { ref } from 'vue';
import { useScoped } from '@zwire/vue';
import { useCollectionRange, useCollectionSize } from '@zwire/vue/collections';
const { orders } = useScoped(account);
const page = ref(0);
const rows = useCollectionRange(orders, () => page.value * 20, 20);
const total = useCollectionSize(orders);
</script>
<template>
<p>{{ total }} orders</p>
<OrderRow v-for="order in rows" :key="order.id" :id="order.id" />
</template>

Arguments accept refs or getters. In a row component, useCollectionItem(orders, () => props.id) updates only when that row changes. A filter option is fixed for the lifetime of the composable.

<script setup lang="ts">
import { useScoped } from '@zwire/vue';
import { useResource } from '@zwire/vue/resource';
const { status, data, pending, refetch } = useResource(useScoped(account).profile);
</script>
<template>
<Spinner v-if="status === 'pending'" />
<button v-else-if="status === 'error'" @click="refetch">Retry</button>
<p v-else :style="{ opacity: pending ? 0.5 : 1 }">{{ data?.name }}</p>
</template>

data keeps the last successful value while refreshing and after an error. Subscribing starts a lazy resource.

Hydrate the scope before any component reads it. In Nuxt, keep the snapshot in useState so it travels in the payload:

app.vue
<script setup lang="ts">
import { provideScope } from '@zwire/vue';
import { useHydrate } from '@zwire/vue/protocol';
const state = useState('zwire', () => ({ balance: 1000 })); // loaded on the server
const scope = provideScope(undefined, { mode: import.meta.server ? 'ssr' : 'client' });
useHydrate(state, { scope });
</script>
<template><NuxtPage /></template>

state maps the keys of hydratable(key, ...) atoms to values. The same object is applied to a scope at most once, and a ref or getter applies later snapshots as they arrive. In a template, <HydrationBoundary :state="state"> hydrates the scope of the enclosing <ScopeProvider>.

When the server serializes state itself, create the scope there, render inside <ScopeProvider :scope="scope">, call dehydrate(scope) from @zwire/core/protocol, and dispose the scope.

0.3 0.4
useStoreScope() useScope()
useAtomValue(signal) useSignal(signal)
useSignal(signal, scope) useSignal(signal, { scope })
useAtom(signal, scope) useAtom(signal, { scope })
useSelector(src, sel, eq, scope) useSelector(src, sel, { equals: eq, scope }) (useSelector(src, sel, eq) is unchanged)
useOptimistic(createOptimisticLayer) from @zwire/vue/hooks, then layer().update(...) useOptimisticLayer() from @zwire/vue/tx, then layer.update(...)
useDraft(createDraft) from @zwire/vue/hooks, then draft().set(...) useDraft() from @zwire/vue/tx, then draft.set(...)
useCollectionTopK(col, k, scope) from @zwire/vue/hooks useCollectionTopK(col, k, { scope }) from @zwire/vue/collections
useSignal outside setup() or an effect scope returned a ref that never updated throws

See the API reference for full signatures and the runnable example.