Skip to main content
cngx-src documentation

optimistic

Functioncommon/interactive/optimistic

projects/common/interactive/optimistic/optimistic.ts

Description#

Creates an optimistic update function for a signal.

Sets the new value immediately (optimistic), then confirms via the async action. On success, applies the server-confirmed value. On failure, rolls back to the previous value.

This is a utility function, not a directive — it composes with any signal.

readonly name = signal('Alice');
readonly [updateName, nameState] = optimistic(
  this.name,
  (value) => this.http.put('/api/name', { name: value })
);

// In template:
<input [value]="name()" (change)="updateName($event.target.value)" />
<ng-container [cngxToastOn]="nameState.state" toastError="Update failed" />

Signature#

optimistic(current: WritableSignal, action)

Parameters#

@paramcurrentWritableSignal
  • The writable signal to update optimistically.
@paramaction
  • Async action that confirms the value. Should return the confirmed value.

Returns#

unknown

Tuple of [applyFn, state].