server library
Experimental server-only async hook hosts for Jaspr.
Import this in server scope. Keep client components on the universal or web entry points. Hooks may span sequential awaits only in these async hosts; ordinary Jaspr async components do not establish a hook session.
Classes
-
AsyncAction<
StateT, InputT> - A stable controller for user-initiated asynchronous state changes.
- AsyncHookBuilder
- An experimental callback-based AsyncHookComponent.
- AsyncHookComponent
- An experimental server-only component that may call hooks across awaits.
- CounterController
- Mutable integer state returned by useCounter.
-
FieldController<
T, V> -
FieldValidators<
T, V> -
FormAutosave<
T> - Optional serialized autosave. A rejected revision is never automatically retried; a subsequent edit, explicit flush, or explicit retry is required.
-
FormController<
T> - FormErrors
-
FormFieldKey<
T, V> - Typed lens into an immutable draft. Paths are stable, including array indexes.
- FormFieldMeta
- FormIssue
- A backend path and rule code survive localization and routing to a control.
- Router-neutral guard registry. Apps call canLeave before route or dialog changes and install their browser unload/history adapter at the app shell.
-
FormOptions<
T> -
FormState<
T> -
FormSubmitContext<
T> -
FormSubmitResult<
T> - Return invalid/uncertain rather than reporting a successful transport write.
-
FormValidationContext<
T> - FormValidationSignal
-
FormValidators<
T> -
GuardedValueNotifier<
T> -
A
ValueNotifierthat ignores assignments after it has been disposed. -
Hook<
R> - Immutable configuration for a reusable piece of lifecycle-aware state.
- HookBuilder
- A hook component that delegates its build to builder.
- HookComponent
-
A stateless Jaspr component whose
buildmethod may call hooks. - HookIdScope
- Provides a stable namespace for descendant useId calls.
-
HookState<
R, H extends Hook< R> > - Mutable lifecycle state associated with one Hook invocation.
-
ListController<
T> - Mutable list state returned by useList.
-
MapController<
K, V> - Mutable map state returned by useMap.
- MutationContext
- A mutation receives the actual transport deadline for this attempt.
-
MutationController<
T, V> - Framework-independent mutation observer; each invocation runs exactly once. Concurrent calls are permitted. Only the latest call updates the snapshot.
-
MutationOptions<
T, V> - Lifecycle callbacks run even after the initiating component unmounts, so cache invalidation completes. Keep UI-only effects outside these callbacks.
-
MutationSnapshot<
T> -
ObjectRef<
T> - A mutable reference whose value survives component rebuilds.
-
OptimisticState<
StateT, UpdateT> - A stable controller for optimistic state layered over authoritative state.
-
OptimisticUpdateHandle<
StateT> - A handle for one pending optimistic update.
- QueryClient
- Shared query cache. Create one per SSR request and one per browser identity. Dispose on logout/identity changes; never share a server instance globally.
- QueryClientProvider
- Provides an explicitly owned cache. The caller disposes client on identity changes and, on the server, after response rendering. Hydrate it before mount.
-
QueryCodec<
T> - Explicit wire codec for SSR. Do not serialize tokens or errors in query data.
- QueryFunctionContext
- Inputs supplied to a repository query, including its per-attempt deadline.
- QueryKey
- Immutable, canonical JSON key. Map order is ignored; list order is significant. Include all filters, pagination and identity-dependent inputs in the key.
-
QueryObserver<
T> - Cache entry and framework-independent observer. Subscriptions own no server I/O.
-
QueryOptions<
T> - Transport-neutral query definition. Retries are opt-in AND require readOnly. A repository must enforce timeout on its actual request, using the context.
-
QueryResult<
T> - Query state plus an explicit refetch operation, which propagates failures.
- QuerySignal
- Cooperative cancellation. Transports should register their cancellation API.
-
QuerySnapshot<
T> - Immutable observable query state. Data can coexist with a refetch error.
-
QueueController<
T> - Mutable first-in, first-out state returned by useQueue.
-
SetController<
T> - Mutable set state returned by useSet.
-
StableEventCallback<
T, R> - A stable callable that always invokes the latest handler supplied to useEvent.
- StatefulHookComponent
-
A stateful Jaspr component whose
State.buildmethod may call hooks. -
Store<
StateT, ActionT> - A mutable state store updated through actions.
- ToggleController
- Mutable boolean state returned by useToggle.
Enums
- ActionConcurrency
- Determines how an AsyncAction handles overlapping dispatches.
- DocumentVisibility
- Whether the browser document is currently visible.
- FormSubmissionStatus
- FormValidationCause
- MediaQueryMatch
- Whether the browser currently matches a CSS media query.
- MutationStatus
- State of the latest mutation invocation. Mutations never retry automatically.
- PreferredColorScheme
- The browser's preferred light or dark color scheme.
- PreferredMotion
- The browser's preferred animation and transition behavior.
- QueryFetchStatus
- QueryStatus
Functions
-
defaultQueryRetryDelay(
int failureCount) → Duration -
formValueEquals(
Object? a, Object? b) → bool - Structural comparison for immutable collections; models may provide equals.
-
use<
R> (Hook< R> hook) → R -
Registers
hookin the currently building hook component and returns its value. -
useAsyncAction<
StateT, InputT> ({required StateT initialState, required AsyncActionHandler< StateT, InputT> action, ActionConcurrency concurrency = ActionConcurrency.sequential}) → AsyncAction<StateT, InputT> - Creates a stable controller for user-initiated asynchronous work.
-
useBrowserRoute<
T> (T serverRoute, T resolve(Uri location), {void onLocationChange(Uri location)?}) → T - Derives a route value from the browser location.
-
useCallback<
T extends Function> (T callback, [List< Object?> keys = const <Object>[]]) → T -
Preserves
callbackuntil one ofkeyschanges or hot reload refreshes it. -
useContext(
) → BuildContext -
Returns the
BuildContextof the currently building hook component. -
useCounter(
[int initialValue = 0]) → CounterController - Creates stable integer state with increment, decrement, and reset operations.
-
useDebounced<
T> (T value, Duration timeout) → T? -
Returns
valueafter it has remained unchanged fortimeout. -
useDisposable<
T> (T create(), void dispose(T value), [List< Object?> keys = const <Object?>[]]) → T -
Creates an owned resource and disposes it when
keyschange or its hook is removed. -
useDocumentVisibility(
) → DocumentVisibility - Returns the document visibility state.
-
useEffect(
Dispose? effect(), [List< Object?> ? keys]) → void - Runs a synchronous browser-client side effect.
-
useEffectOnce(
Dispose? effect()) → void -
Runs
effectduring the hook's first browser-client build. -
useEvent<
T, R> (R handler(T value)) → StableEventCallback< T, R> -
Returns a stable callback that always invokes the latest
handler. -
useExternalStore<
T> (ExternalStoreSubscribe subscribe, T getSnapshot(), {T getServerSnapshot()?, ExternalStoreSnapshotEquals< T> ? equals}) → T - Reads and subscribes to an external immutable snapshot.
-
useField<
T, V> (FormController< T> form, FormFieldKey<T, V> key, {FieldValidators<T, V> validators = const FieldValidators()}) → FieldController<T, V> -
useForm<
T> (FormOptions< T> options, {List<Object?> keys = const []}) → FormController<T> - Owns a draft for the component lifetime. New defaultValues do not replace edits on a rebuild; call reset explicitly after loading another record.
-
useFormAutosave<
T> (FormController< T> form, {Duration debounce = const Duration(milliseconds: 600), bool canSave()?, Future<bool> save()?}) → FormAutosave<T> -
useFormState<
T, S> (FormController< T> form, S selector(FormState<T> ), {bool equals(S, S)?}) → S - Subscribe at the smallest component that renders the selected state.
-
useFuture<
T> (Future< T> ? future, {T? initialData, bool preserveState = true}) → AsyncSnapshot<T> -
Subscribes to
futureon the browser client and returns its latest snapshot. -
useGuardedState<
T> (T initialData) → GuardedValueNotifier< T> - Creates a GuardedValueNotifier that rebuilds its owning component when changed and silently drops assignments made after the component unmounts.
-
useId(
{String prefix = 'jh'}) → String - Returns an HTML id that is stable across rebuilds and hot reload.
-
useImperativeHandle<
T extends Object> (ObjectRef< T?> ? target, T createHandle(), [List<Object?> ? keys]) → void -
Exposes a generated handle through
targetuntil this hook is replaced or removed. -
useInherited<
T extends InheritedComponent> ({Object? aspect}) → T? -
Reads and subscribes to the nearest Jaspr inherited component of type
T. -
useInterval(
VoidCallback callback, Duration? interval, {bool immediate = false}) → void -
Repeatedly invokes the latest
callbackeveryintervalon the browser client. -
useIsMounted(
) → IsMounted -
Returns a stable callback that becomes
falseafter hook disposal. -
useLatest<
T> (T value) → ObjectRef< T> -
Keeps the latest
valuein a stable reference without requesting rebuilds. -
useList<
T> ([Iterable< T> initialValue = const <Never>[]]) → ListController<T> -
Creates stable list state initialized with a snapshot of
initialValue. -
useListenable<
T extends Listenable?> (T listenable) → T -
Returns
listenableand rebuilds when it notifies on the browser client. -
useListenableSelector<
R> (Listenable? listenable, R selector()) → R -
Rebuilds only when the result of
selectorchanges. -
useLocation(
) → Uri? - Returns the current document location.
-
useMap<
K, V> ([Map< K, V> initialValue = const <Never, Never>{}]) → MapController<K, V> -
Creates stable map state initialized with a snapshot of
initialValue. -
useMediaQuery(
String query) → MediaQueryMatch -
Returns whether the document matches
query. -
useMemoized<
T> (T valueBuilder(), [List< Object?> keys = const <Object>[]]) → T -
Evaluates
valueBuilderonce and caches its value untilkeyschange or development hot reload invalidates the cache. -
useMount(
VoidCallback effect) → void -
Runs
effectduring the hook's first browser-client build. -
useMutation<
T, V> (MutationOptions< T, V> options) → MutationController<T, V> - Owns mutation state until unmount. No mutation starts during SSR. Options update on rebuild; each invocation retains the callbacks it started with.
-
useOnDocumentVisibilityChange(
DocumentVisibilityCallback callback) → void -
Calls
callbackwhen document visibility changes after initial browser synchronization. -
useOnListenableChange(
Listenable? listenable, VoidCallback listener) → void -
Invokes
listenerwhenlistenablenotifies on the browser client. -
useOnMediaQueryChange(
String query, MediaQueryCallback callback) → void -
Calls
callbackwhenquerychanges after initial browser synchronization. -
useOnPreferredColorSchemeChange(
PreferredColorSchemeCallback callback) → void -
Calls
callbackwhen the preferred scheme changes after initial browser synchronization. -
useOnPreferredMotionChange(
PreferredMotionCallback callback) → void -
Calls
callbackwhen the browser's preferred motion behavior changes. -
useOnStreamChange<
T> (Stream< T> ? stream, {void onData(T event)?, void onError(Object error, StackTrace stackTrace)?, void onDone()?, bool? cancelOnError}) → StreamSubscription<T> ? -
Listens to
streamon the browser client and invokes the latest callbacks. -
useOnWindowFocus(
void callback(), {bool includeVisibilityChange = true}) → void -
Calls
callbackwhen the window regains focus. -
useOptimistic<
StateT, UpdateT> (StateT authoritativeState, StateT reducer(StateT current, UpdateT update)) → OptimisticState< StateT, UpdateT> -
Layers optimistic updates over
authoritativeState. -
usePostFrameEffect(
Dispose? effect(), [List< Object?> ? keys]) → void -
Runs
effectafter the next completed browser-client frame. -
usePostFrameUpdateEffect(
Dispose? effect(), [List< Object?> ? keys]) → void -
Runs
effectafter a completed browser frame for updates, skipping the frame that mounted the hook. -
usePreferredColorScheme(
) → PreferredColorScheme - Returns the browser's preferred color scheme.
-
usePreferredMotion(
) → PreferredMotion - Returns the browser's preferred animation and transition behavior.
-
usePrevious<
T> (T value) → T? -
Returns the value supplied during the preceding build, or
nullinitially. -
useQuery<
T> (QueryOptions< T> options, {QueryClient? client}) → QueryResult<T> - Subscribes to a keyed query. SSR only reads prefetched cache data and starts no I/O, subscriptions or timers. Hydrate the cache before the first client render for matching HTML; subscriptions/fetching activate after that frame. Key changes unsubscribe the old query. The last observer cancels its fetch.
-
useQueryClient(
) → QueryClient - Reads the nearest cache without allocating one. Works during SSR.
-
useQueryLifecycle(
QueryClient client) → void - Installs one browser focus/reconnect bridge per app cache. No work on SSR; removes listeners on unmount or client replacement. Call once in the shell.
-
useQueue<
T> ([Iterable< T> initialValue = const <Never>[]]) → QueueController<T> -
Creates stable queue state initialized with a snapshot of
initialValue. -
useReducer<
StateT, ActionT> (Reducer< StateT, ActionT> reducer, {required StateT initialState, required ActionT initialAction}) → Store<StateT, ActionT> - Creates a reducer-backed Store.
-
useRef<
T> (T initialValue) → ObjectRef< T> - Preserves a mutable ObjectRef across builds and hot reload.
-
useSet<
T> ([Iterable< T> initialValue = const <Never>[]]) → SetController<T> -
Creates stable set state initialized with a snapshot of
initialValue. -
useState<
T> (T initialData) → ValueNotifier< T> -
Creates a
ValueNotifierthat rebuilds its owning component when changed. Async server hook hosts expose a read-only initial snapshot instead. -
useStream<
T> (Stream< T> ? stream, {T? initialData, bool preserveState = true}) → AsyncSnapshot<T> -
Subscribes to
streamon the browser client and returns its latest snapshot. -
useStreamController<
T> ({bool sync = false, VoidCallback? onListen, VoidCallback? onCancel, List< Object?> ? keys}) → StreamController<T> - Creates a broadcast StreamController and closes it on hook disposal.
-
useTimeout(
VoidCallback callback, Duration? delay) → void -
Invokes the latest
callbackonce afterdelayon the browser client. -
useToggle(
[bool initialValue = false]) → ToggleController - Creates stable boolean state with toggle and reset operations.
-
useUnmount(
VoidCallback effect) → void -
Runs
effectwhen the hook is removed from a browser-client component. -
useUpdateEffect(
Dispose? effect(), [List< Object?> ? keys]) → void -
Runs
effectduring updates while skipping the initial client build. -
useValueChanged<
T, R> (T value, R? valueChange(T oldValue, R? oldResult)) → R? -
Calls
valueChangewhenvaluechanges and returns its latest result. -
useValueListenable<
T> (ValueListenable< T> valueListenable) → T -
Subscribes to
valueListenableand returns its current value. -
useValueNotifier<
T> (T initialData, [List< Object?> ? keys]) → ValueNotifier<T> -
Creates a
ValueNotifierand disposes it when its hook is removed.
Typedefs
-
AsyncActionHandler<
StateT, InputT> = FutureOr< StateT> Function(StateT previousState, InputT input) - Computes the next state for an asynchronous action.
-
AsyncFormValidator<
T> = Future< FormErrors?> Function(FormValidationContext<T> context) - Dispose = void Function()
- A cleanup function returned by an effect.
- DocumentVisibilityCallback = void Function(DocumentVisibility previous, DocumentVisibility current)
- Callback invoked after an established document visibility value changes.
-
ExternalStoreSnapshotEquals<
T> = bool Function(T previous, T current) - Decides whether two external-store snapshots represent the same value.
- ExternalStoreSubscribe = Dispose Function(VoidCallback notify)
-
Subscribes
notifyto an external store and returns its unsubscribe callback. -
FormValidator<
T> = FormErrors? Function(FormValidationContext< T> context) - IsMounted = bool Function()
- Function that reports whether its hook remains mounted.
- MediaQueryCallback = void Function(MediaQueryMatch previous, MediaQueryMatch current)
- Callback invoked after an established media-query result changes.
- PreferredColorSchemeCallback = void Function(PreferredColorScheme previous, PreferredColorScheme current)
- Callback invoked after an established preferred color scheme changes.
- PreferredMotionCallback = void Function(PreferredMotion previous, PreferredMotion current)
- Callback invoked after an established preferred-motion value changes.
-
Reducer<
StateT, ActionT> = StateT Function(StateT state, ActionT action) - Combines a state and action into the next state.
Exceptions / Errors
- ActionCancelledException
- Thrown when a queued action is invalidated before it starts.
- ActionDroppedException
- Thrown when ActionConcurrency.drop rejects an overlapping dispatch.
- QueryCancelled
- A cancelled query must never publish a late result into the cache.