Stepperize v9Explore the changes
Skip to Content
Stepperize

TanStack Form

A complete flow with validation, review and final submission.

This two-step example keeps the two jobs apart: TanStack Form owns the fields of the profile step, and Stepperize owns the flow, what the step saved and the final submission.

npm install @stepperize/react @tanstack/react-form zod

TanStack Form accepts Standard Schema validators directly, so the same profileSchema is used by the form and by the step, with no adapter.

Complete example

Pass onFinish from your application to perform the final request. It should reject on failure; the flow then stays open and the person can retry.

signup.tsx
"use client";

import { defineStepper } from "@stepperize/react";
import { useForm } from "@tanstack/react-form";
import { useState } from "react";
import { z } from "zod";

const profileSchema = z.object({
  name: z.string().min(1, "Enter your name"),
  email: z.string().email("Enter a valid email"),
});
type Profile = z.infer<typeof profileSchema>;

const signup = defineStepper([
  { id: "profile", title: "Profile", schema: profileSchema },
  { id: "review", title: "Review" },
]);

type Props = { onFinish: (profile: Profile) => Promise<void> };

export function Signup({ onFinish }: Props) {
  return (
    <signup.Provider
      linear
      // `output` is what the schemas produced. Returning the promise keeps the
      // flow pending while it runs, and unfinished if it rejects.
      onFinish={async (output) => {
        if (output.profile) await onFinish(output.profile);
      }}
    >
      <Flow />
    </signup.Provider>
  );
}

function Flow() {
  const stepper = signup.useStepperContext();
  if (stepper.isFinished) return <p role="status">Saved successfully.</p>;

  return stepper.match({
    profile: () => <ProfileForm />,
    review: () => <Review />,
  });
}

function ProfileForm() {
  const stepper = signup.useStepperContext();
  const form = useForm({
    defaultValues: stepper.data.profile ?? { name: "", email: "" },
    validators: { onSubmit: profileSchema },
    onSubmit: async ({ value }) => {
      await stepper.next(value);
    },
  });

  return (
    <form
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        event.stopPropagation();
        void form.handleSubmit();
      }}
    >
      {(["name", "email"] as const).map((name) => (
        <form.Field key={name} name={name}>
          {(field) => (
            <div>
              <label>
                {name === "name" ? "Name" : "Email"}
                <input
                  name={field.name}
                  type={name === "email" ? "email" : "text"}
                  value={field.state.value}
                  onBlur={field.handleBlur}
                  onChange={(event) => field.handleChange(event.target.value)}
                  aria-invalid={field.state.meta.errors.length > 0}
                />
              </label>
              {field.state.meta.errors.map((error) => (
                <p role="alert" key={error?.message}>
                  {error?.message}
                </p>
              ))}
            </div>
          )}
        </form.Field>
      ))}

      <form.Subscribe selector={(state) => state.isSubmitting}>
        {(isSubmitting) => (
          <button type="submit" disabled={isSubmitting}>
            Review
          </button>
        )}
      </form.Subscribe>
    </form>
  );
}

function Review() {
  const stepper = signup.useStepperContext();
  const profile = stepper.data.profile;
  const [error, setError] = useState("");

  async function finish() {
    setError("");
    try {
      await stepper.next();
    } catch {
      setError("Could not save. Try again.");
    }
  }

  return (
    <section>
      <h2>Review</h2>
      <p>
        {profile?.name} · {profile?.email}
      </p>
      {error && <p role="alert">{error}</p>}
      <button type="button" disabled={stepper.isPending} onClick={() => stepper.prev()}>
        Edit
      </button>
      <button type="button" disabled={stepper.isPending} onClick={finish}>
        {stepper.isPending ? "Saving…" : "Finish"}
      </button>
    </section>
  );
}

Why this works

  • One provider owns the flow. Every component below reads it with useStepperContext().
  • The form validates the fields; the step validates the move. Both use profileSchema. The form shows field errors as it is configured to; the step's schema guarantees next() cannot leave the step with invalid data, whatever called it.
  • next(values) saves and moves in one update. The profile is stored, the step becomes complete and the review renders, in a single render.
  • Going back fills the form. Edit calls prev(), the form mounts again and takes stepper.data.profile as its initial values.
  • The request is part of the last move. onFinish returns its promise, so isPending is true while it runs. If it rejects, next() rejects, the flow is not finished and the person can try again. Once it resolves, stepper.isFinished is true and a second press cannot submit twice.
  • What is sent is the schema's output. onFinish receives what profileSchema produced, so nothing has to be parsed again.

Errors that come from the step

When a rule lives only in the step's schema, next() returns its issues. Return them from onSubmit validation so they show next to their fields:

const form = useForm({
  defaultValues: stepper.data.profile ?? { name: "", email: "" },
  validators: {
    onSubmitAsync: async ({ value }) => {
      const result = await stepper.next(value);
      if (result.accepted || !result.issues) return;
      const fields: Record<string, string> = {};
      for (const issue of result.issues) {
        const field = issue.path?.[0];
        if (typeof field === "string") fields[field] ??= issue.message;
      }
      return { fields };
    },
  },
});

Here the step's schema is the only validation: the form collects the values and the step judges them.

Keeping what was typed

next(value) stores the values even when the step's schema rejects them, and the form reads them back as defaultValues when it mounts again. To keep fields that were never submitted, see Keeping steps mounted.

Compare with React Hook Form and Conform, or go back to the patterns.

Edit on GitHub

Last updated on

On this page