Stepperize v9Explore the changes
Skip to Content
Stepperize

Moving between steps

next, prev and goTo, their results, linear flows, guards and finishing.

Three methods move the flow. Each returns a promise that resolves with what happened, and none of them throws for an expected outcome.

MethodBehavior
next(data?)Saves data for the current step, validates the step, and moves forward. On a final step it finishes the flow.
prev()Goes back to the step the person came from. Never validates.
goTo(id)Jumps to a step. Never validates.
<button type="button" disabled={stepper.isFirst} onClick={() => stepper.prev()}>
  Back
</button>
<button type="button" onClick={() => stepper.next()}>
  {stepper.isLast ? "Finish" : "Continue"}
</button>

The lifecycle of a move describes each stage. This page is about using them.

Read the result

Await the call when what you do next depends on it.

async function onContinue() {
  const result = await stepper.next(values);

  if (result.accepted) {
    if (result.to === null) toast("Order placed");
    return;
  }
  if (result.reason === "invalid") focusFirstError(result.issues);
}
ReasonMeaning
invalidThe step's schema rejected its data. issues says why.
guardYour guard returned false.
policyThe flow is linear and the step is not reachable yet.
pendingAnother move is still running.
boundaryprev() was called with nowhere to go back to.
finishednext() was called after the flow finished.
cancelledreset(), restore() or unmounting interrupted the move.

Linear flows

By default any step can be opened at any time, which suits settings pages and tabs. Pass linear for a flow that has to be done in order.

const stepper = checkout.useStepper({ linear: true });

In a linear flow:

  • next() is the only way forward, and it validates.
  • goTo(id) reaches the current step and the steps that are complete. Anything else resolves with reason: "policy", without calling the guard.
  • prev() always works.
  • canGoTo(id) tells you in advance, which is what disables the triggers of the primitives.
const flow = checkout.create({ linear: true });

flow.canGoTo("review"); // false
(await flow.goTo("review")).accepted; // false, reason "policy"

await flow.next(); // shipping is complete
await flow.next(); // payment is complete
await flow.goTo("shipping"); // allowed: it is complete
await flow.goTo("payment"); // allowed

linear decides which steps can be opened. It does not validate anything by itself: validation comes from each step's schema.

Editing a step that was already complete

A step is complete while its data is what next() validated. When setData writes something different to a complete step, or a next(data) on it is rejected, the step is no longer complete. In a linear flow the steps that were completed after it are no longer complete either, so nothing past an edited step can be opened without validating it again. Their data is kept.

const flow = checkout.create({ linear: true });
await flow.next({ address: "12 Analytical Ave" });
await flow.next({ card: "4242424242424242" }); // now on review

await flow.goTo("shipping");
flow.setData("shipping", { address: "" });

flow.state("payment"); // "pending": it comes after an edited step
flow.canGoTo("payment"); // false
flow.data.payment; // still there

Without linear, only the edited step stops being complete.

Edit from the review and come back

A review step usually links back to the earlier steps. After the edit, walk forward with next() until the review is reached again. Each call validates the data that is already stored, so the steps in between pass without the person seeing them, and the walk stops at the first one that is no longer valid.

async function saveAndReturn(values: unknown) {
  let result = await stepper.next(values);
  while (result.accepted && result.to !== "review") {
    result = await stepper.next();
  }
}

Use the result, not stepper, inside the loop: the stepper you hold is the flow as it was when your component rendered.

The same option changes the markup of the primitives, from tabs to an ordered list of steps. See Accessibility.

Guard a move

A guard runs before every next, prev and goTo, after validation. Return false to cancel the move; anything else allows it.

checkout.useStepper({
  guard: ({ from, direction }) => {
    if (direction === "prev" && from.id === "payment") {
      return window.confirm("Discard the card details?");
    }
  },
});
FieldDescription
fromThe step being left.
toThe step being entered, or null when the flow is finishing.
direction"next", "prev" or "goTo".
dataThe data of every step as it will be if the move is accepted.
signalAborted if the move is cancelled. Pass it to fetch.

Use the schema to say whether a step's data is valid, and the guard for everything else: asking the server, confirming a destructive move, blocking the exit from a step.

A guard is called for moves only. setData, reset and restore do not run it.

Async work

A guard, schema or onFinish that returns a promise makes the move asynchronous. While it runs, isPending is true and other moves are refused, so you do not need to protect against double clicks yourself.

<button type="button" disabled={stepper.isPending} onClick={() => stepper.next()}>
  {stepper.isPending ? "Checking…" : "Continue"}
</button>

Stepper.Prev, Stepper.Next and the triggers already do this. They use aria-disabled rather than disabled while pending, so the button that was pressed keeps keyboard focus.

Cancelling a move does not undo what your guard already did on the server. Use the signal to stop the request, and make the endpoint safe to call twice.

Jump to a step

<button type="button" onClick={() => stepper.goTo("shipping")}>
  Edit address
</button>

goTo takes ids of the definition only: a typo is a type error. For a value that comes from outside, such as the URL, use the step option, which ignores what it does not know.

Finish the flow

next() on the last step validates it and ends the flow: the result has to: null and onFinish is called once.

const stepper = checkout.useStepper({
  onFinish: (output) => api.createOrder(output),
});

if (stepper.isFinished) return <p role="status">Order placed.</p>;

onFinish receives two arguments:

  • output: what the schema of every complete step produced, with transforms, coercions and defaults applied. This is what you send.
  • data: every step as it was typed, including drafts of steps that were never completed.

stepper.isLast is true when next() is certain to finish, which is what the label of your button needs. stepper.isFinished is true once it has, so you do not need a state of your own to show the confirmation.

The flow stays on its last step afterwards, and another next() is refused with the reason finished: a second press does not submit twice. The flow opens again as soon as it changes: any move, a setData with a new value, reset() or restore(). Stepper.Root has data-finished meanwhile, and Stepper.Next is aria-disabled.

When submitting can fail

Return the promise of your request from onFinish. The flow stays pending while it runs and only becomes finished when it resolves.

const stepper = checkout.useStepper({
  onFinish: async (output) => {
    const response = await fetch("/api/orders", {
      method: "POST",
      body: JSON.stringify(output),
    });
    if (!response.ok) throw new Error("Could not place the order.");
  },
});

async function placeOrder() {
  try {
    await stepper.next();
  } catch {
    setError("Could not place the order. Try again.");
  }
}

While the request runs isPending is true and other moves are refused. If it rejects, next() rejects with the same error and isFinished stays false, so the person can press the button again. Catch the error where you call next(), or inside onFinish if you would rather not throw; in that case remember that returning normally finishes the flow.

A request that has to be cancellable can still go in the guard, which receives an abort signal; to is null on the finishing move.

React to a step change

onChange is called after every change with the new snapshot. To act on the step only, compare it:

const last = useRef<string | null>(null);

const stepper = checkout.useStepper({
  onChange: (snapshot) => {
    if (snapshot.step !== last.current) analytics.track("step_viewed", { step: snapshot.step });
    last.current = snapshot.step;
  },
});

In a component that only needs to react to what is rendered, an effect on the id works as well:

useEffect(() => {
  window.scrollTo({ top: 0 });
}, [stepper.current.id]);

Start over

CallResult
reset()Back to the snapshot the flow started with: its first step and no data, unless you passed a snapshot.
restore({ step: "shipping", history: [] })Go to a step and keep the data and the completed steps.
restore({ data: {}, complete: [] })Clear the data and the completion and stay on the current step.

Both are immediate, cancel a move that is running, and skip the guard.

Next: validation.

Edit on GitHub

Last updated on

On this page