Reading state

The ways to read a mutation's state: status() and its boolean flags, hasValue() to narrow value(), snapshot() for an exhaustive @switch, input() to know what was submitted, and a typed error(). Each block shows the template that renders it. Source

Create user

Create a user, then submit an empty name, then reset. A create takes 2 s (an artificial delay).

// TError types error() and onError; mutation() does not check it at runtime.
protected readonly createUser = mutation<string, User, ApiError>({
  mutationFn: (name, abortSignal) => this.server.createUser(name, abortSignal),
});

status() and the flags

status() is 'idle', 'pending', 'success' or 'error', and each flag is one of them as a boolean. The submit button above reads isPending():

<button type="submit" [disabled]="createUser.isPending()">
  {{ createUser.isPending() ? 'Creating…' : 'Create user' }}
</button>
status
idle
isIdle / isPending / isSuccess / isError
true / false / false / false

hasValue()

A type guard: inside the @if, value() is User, not User | undefined, so no ?. or !. The same guard works in computed() (last created: —). The card stays after an error: only a new success or reset() replaces value().

@if (createUser.hasValue()) {
  <div class="card">
    <strong>{{ createUser.value().name }}</strong>
    <span>#{{ createUser.value().id }}</span>
  </div>
} @else {
  <p class="hint">No user created yet.</p>
}

No user created yet.

snapshot()

status, value and error in one read, as a union discriminated by status: each @case narrows it. snap.value is a User in 'success', snap.error an ApiError in 'error'.

@let snap = createUser.snapshot();
@switch (snap.status) {
  @case ('idle') {
    <p class="hint">Idle.</p>
  }
  @case ('pending') {
    <p class="hint">Pending, previous value: {{ snap.value?.name ?? 'none' }}.</p>
  }
  @case ('success') {
    <p class="hint">Created {{ snap.value.name }}.</p>
  }
  @case ('error') {
    <p class="hint">
      <span class="error-text">{{ snap.error.message }}</span>, previous value:
      {{ snap.value?.name ?? 'none' }}.
    </p>
  }
}

Idle.

input() and a typed error

input() is what the latest mutate() was called with, set at once: the messages name the user being created, and Retry sends it again. error.code compiles because the mutation is declared as mutation<string, User, ApiError>; only 'unavailable' is worth retrying. Check "Fail the next call", then create a user.

@if (createUser.error(); as error) {
  <p class="error-text" role="alert">
    Could not create "{{ createUser.input() }}": {{ error.message }}
  </p>
  @if (error.code === 'unavailable') {
    <button type="button" (click)="retry()">Retry "{{ createUser.input() }}"</button>
  }
} @else if (createUser.isPending()) {
  <p class="hint">Creating "{{ createUser.input() }}"…</p>
} @else {
  <p class="hint">No error.</p>
}

No error.