Saving and resuming
The flow owns its state. One snapshot goes in, one callback comes out.
The flow always holds its own state. You do not pass the current step or the data on every render and wait for callbacks to apply them; you give the flow a starting point, and it tells you about every change.
That exchange uses one object, the snapshot: everything a flow needs to continue later.
type Snapshot = {
step: string; // the current step
history: string[]; // the path taken, which prev() walks back
data: object; // the data of every step, by id
complete: string[]; // the steps next() has validated, in that order
};It is plain JSON when your data is. Each binding exports it typed for your
steps, as Snapshot<typeof checkout.steps>.
On this page, stepper is the value of the signal injectStepper() returns:
this.stepper() in a class, stepper() in a template.
Save and resume
readonly stepper = checkout.injectStepper({
snapshot: saved,
onChange: (snapshot) => save(snapshot),
});snapshotis where the flow starts. Pass any part of it, for example only{ step: "payment" }or only{ data }.onChangeis called with the whole snapshot after the step, the data or the completion changes.
snapshot is read once, when the flow is created. Passing a different
object later does nothing; that is what restore is
for.
What onChange reports
| Change | onChange |
|---|---|
An accepted next, prev or goTo | Yes |
A next() the schema rejected | Yes: the data that was passed is kept |
setData with a new value | Yes |
setData with the value the step already has | No: nothing changed |
validate() | No |
reset, restore | Yes |
isPending or isFinished changing | No |
| A move the guard refused | No |
In the browser, without a mismatch
A server cannot read localStorage, so a flow that starts from it would
render differently on the server and in the browser. Start from what both
know, and apply the saved snapshot after mounting.
import { afterNextRender, Component } from "@angular/core";
import { checkout } from "./checkout";
@Component({ selector: "app-checkout", template: `…` })
export class Checkout {
readonly stepper = checkout.injectStepper({
onChange: (snapshot) => localStorage.setItem("checkout", JSON.stringify(snapshot)),
});
constructor() {
// Runs in the browser only, once the page has rendered (and hydrated).
afterNextRender(() => {
const saved = localStorage.getItem("checkout");
if (saved) this.stepper().restore(JSON.parse(saved));
});
}
}afterNextRender never runs on the server, so localStorage is only read in
the browser. To have the first HTML on the saved step, resolve the snapshot on
the server: see saving to a server.
In an app that only renders in the browser, reading it directly is fine:
readonly stepper = checkout.injectStepper({
snapshot: JSON.parse(localStorage.getItem("checkout") ?? "{}"),
onChange: (snapshot) => localStorage.setItem("checkout", JSON.stringify(snapshot)),
});Saving to a server
onChange is also called by setData. If you write drafts on every
keystroke, debounce the request.
A draft loaded on the server is the best starting point: the first render already shows the right step.
import { inject } from "@angular/core";
import type { Routes } from "@angular/router";
import { CheckoutPage } from "./checkout.page";
import { DraftApi } from "./draft-api";
// With provideRouter(routes, withComponentInputBinding()) in app.config.ts.
export const routes: Routes = [
{
path: "checkout",
component: CheckoutPage,
resolve: { draft: () => inject(DraftApi).load() },
},
];import { Component, inject, input } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { debounceTime, Subject, switchMap } from "rxjs";
import type { Snapshot } from "@stepperize/angular";
import { checkout } from "./checkout";
import { DraftApi } from "./draft-api";
type CheckoutSnapshot = Snapshot<typeof checkout.steps>;
@Component({ selector: "app-checkout-page", template: `…` })
export class CheckoutPage {
readonly #api = inject(DraftApi);
readonly #changes = new Subject<CheckoutSnapshot>();
/** Bound from the route's resolver. */
readonly draft = input<CheckoutSnapshot | null>();
readonly stepper = checkout.injectStepper(() => ({
snapshot: this.draft() ?? undefined,
onChange: (snapshot) => this.#changes.next(snapshot),
}));
constructor() {
this.#changes
.pipe(
debounceTime(500),
switchMap((snapshot) => this.#api.save(snapshot)),
takeUntilDestroyed(),
)
.subscribe();
}
}The resolver runs before the component is created, so the input is set when
the flow reads snapshot. Resolved data only reaches inputs with
withComponentInputBinding(); without it the input stays undefined and the
flow starts on the first step, with no error. With provideClientHydration(),
HttpClient hands the server's response to the browser, so the resolver does
not fetch the draft twice.
Loading a draft later
When the draft arrives after the first render, apply it with restore. It
replaces the state without validation or guards, and cancels a move that is
running.
readonly #api = inject(DraftApi);
readonly #destroyRef = inject(DestroyRef);
constructor() {
afterNextRender(() => {
this.#api
.load()
.pipe(takeUntilDestroyed(this.#destroyRef))
.subscribe((draft) => {
if (draft) this.stepper().restore(draft);
});
});
}restore replaces the parts you pass and keeps the others:
| Call | Effect |
|---|---|
restore(snapshot) | Replace everything. |
restore({ data }) | Replace the data of every step; stay on the current step. |
restore({ step: "review" }) | Go to a step without validation or guards. |
restore({ complete: [] }) | Clear the completion. |
Each part is replaced as a whole: restore({ data: { shipping } }) leaves the
other steps without data. To change one step, use setData.
Old snapshots
Flows change. When a saved snapshot names a step that no longer exists, it is
dropped from step, history and complete, and the flow starts on the
first step if step was the one that disappeared. A snapshot from an older
version of your flow never throws.
The data of each step is not checked when it is loaded. It is validated like
any other data, the next time next() runs on that step.
A snapshot holds what was typed, not the schemas' output, so a step loaded as
complete has no entry in stepper.output yet. The next() that finishes the
flow validates those steps once more before calling onFinish. If the saved
data no longer passes, because the schema changed since, the flow does not
finish: next() resolves with reason: "invalid", the step stops being
complete and stepper.issues(id) says why. To find out earlier, call
stepper.validate(id) after loading the draft.
restore keeps the output of every complete step whose data it did not
replace, so restore({ step: "review" }) loses nothing.
Starting over
reset() goes back to the snapshot the flow started with, and cancels a move
that is still running. Remember to delete your saved copy: reset() reports
the fresh snapshot through onChange like any other change.
startOver() {
this.stepper().reset();
localStorage.removeItem("checkout");
}Reading the snapshot
stepper.snapshot() returns the current one at any time, for example to send
it with a support request, or to read the completed steps.
What not to save
A snapshot contains everything the steps stored. Remove what should not be written to storage before saving it.
onChange: (snapshot) => {
const { payment: _payment, ...data } = snapshot.data;
localStorage.setItem("checkout", JSON.stringify({ ...snapshot, data }));
},Next: the step in the URL.
Last updated on