콘텐츠로 이동

@zwire/solid

이 콘텐츠는 아직 번역되지 않았습니다.

Solid 2 primitives for @zwire/core: read-through accessors, optimistic mutations, incremental lists, async resources and SSR hydration.

Values always read through to signal.get(), and subscriptions are owned by Solid’s current reactive owner (onCleanup), including after server rendering.

The adapter uses Solid 2 callable contexts and owned writes. Solid 1.x applications require a separate integration.

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

Every primitive takes an optional options object as its last argument; { scope } overrides the scope from ScopeProvider. Reactive fields are accessors.

import { atom } from '@zwire/core';
import { useAtom, useSelector, useSignal } from '@zwire/solid';
const count = atom(0);
function Counter() {
const value = useSignal(count); // Accessor<number>
const parity = useSelector(count, (n) => n % 2);
const [, setCount] = useAtom(count);
return <button onClick={() => setCount((n) => n + 1)}>{value()} ({parity()})</button>;
}
// 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 }),
}));
import { ScopeProvider, useScoped, useSignal } from '@zwire/solid';
function Balance() {
const { balance } = useScoped(account); // the instance for the nearest ScopeProvider
const available = useSignal(balance);
return <output>{available()}</output>;
}
export function App() {
// Without a `scope` prop the provider creates a scope and disposes it with its owner.
return (
<ScopeProvider>
<Balance />
</ScopeProvider>
);
}

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).

import { useOptimisticAction } from '@zwire/solid/tx';
function Reserve() {
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) },
);
return (
<>
<button disabled={reserve.pending()} onClick={() => reserve.run(150)}>
Reserve 150
</button>
<Show when={reserve.error()}>
<p role="alert">Could not reserve</p>
</Show>
</>
);
}
  • 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 its owner is disposed, 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 disposing the owner reverts it. useDraft() gives the same kind of handle for an STM draft (open, get, set, commit, discard); draft.get(signal) is reactive.

import { useCollectionItem, useCollectionRange, useCollectionSize } from '@zwire/solid/collections';
function Orders(props: { page: number }) {
const { orders } = useScoped(account);
const rows = useCollectionRange(orders, () => props.page * 20, 20);
const total = useCollectionSize(orders);
return (
<>
<p>{total()} orders</p>
<For each={rows()}>{(order) => <OrderRow id={order.id} />}</For>
</>
);
}
function OrderRow(props: { id: number }) {
const { orders } = useScoped(account);
const order = useCollectionItem(orders, () => props.id); // updates only when this row changes
return <li>{order()?.qty}</li>;
}

Arguments accept accessors. A filter option is fixed for the lifetime of the primitive.

import { useResource, useSuspenseResource } from '@zwire/solid/resource';
function Profile() {
const profile = useResource(useScoped(account).profile);
return (
<Switch>
<Match when={profile.status() === 'pending'}>
<Spinner />
</Match>
<Match when={profile.status() === 'error'}>
<button onClick={profile.refetch}>Retry</button>
</Match>
<Match when={profile.data()}>{(data) => <p>{data().name}</p>}</Match>
</Switch>
);
}
// Under <Loading> and <Errored>:
function ProfileName() {
const profile = useSuspenseResource(useScoped(account).profile);
return <p>{profile().name}</p>;
}

useResource never suspends, and data() keeps the last successful value while refreshing and after an error. useSuspenseResource shows the nearest <Loading> fallback during the first load, sends a load error to <Errored>, and keeps the last value visible while refreshing.

Hydrate the scope before any component reads it. At the root of the app, including a SolidStart root:

import { isServer } from '@solidjs/web';
import { ScopeProvider } from '@zwire/solid';
import { HydrationBoundary } from '@zwire/solid/protocol';
import type { HydratedState } from '@zwire/core/protocol';
import type { Element as SolidElement } from 'solid-js';
export function Root(props: { state: HydratedState; children?: SolidElement }) {
return (
<ScopeProvider mode={isServer ? 'ssr' : 'client'}>
<HydrationBoundary state={props.state}>{props.children}</HydrationBoundary>
</ScopeProvider>
);
}

state maps the keys of hydratable(key, ...) atoms to values. The same object is applied to a scope at most once. useHydrate(state, { scope }) does the same from a component body and accepts an accessor to apply later snapshots.

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/solid/hooks, then layer().update(...) useOptimisticLayer() from @zwire/solid/tx, then layer.update(...)
useDraft(createDraft) from @zwire/solid/hooks, then draft().set(...) useDraft() from @zwire/solid/tx, then draft.set(...)
useCollectionTopK(col, k, scope) from @zwire/solid/hooks useCollectionTopK(col, k, { scope }) from @zwire/solid/collections

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