Sub topic 9
Reviewing and Submitting
The review step is the last screen of a guided flow. It shows the user what they entered, lets them fix mistakes, and sends the data. This chapter assumes you know the flow state model (current, history, data, errors), per-step validate and next functions, and branching from earlier chapters. All code is framework-neutral TypeScript.
What the review step is for
Per-step validation checks one step at a time, and that isn't enough on its own. Three things can still go wrong by the time the user reaches the end:
- The user went back, changed an earlier answer, and moved forward again. A later step may now be invalid, or may no longer be on the path.
- A branch changed. Data from a branch the user left (for example, a company name after switching from "business" to "personal") is still in
data. - The user can't see everything at once. A summary lets them catch a typo before it becomes a support ticket.
So the review step does four jobs:
- Show the answers from the steps on the current path.
- Let the user jump back to any of them.
- Re-validate the whole path.
- Submit once, and report the outcome in a way the user can act on.
Derive the path from the data
In a branching flow, history records where the user has been, not where the flow goes now. After an edit, those can differ. For the review and for submission, compute the path by walking next() from the first step with the current data.
The first block repeats the types and example steps from earlier chapters so the code is self-contained. It adds a fieldsByStep map that says which fields each step owns.
type Data = Record<string, string>;
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
const steps: Record<string, Step> = {
account: {
id: "account",
validate: (d) =>
/^\S+@\S+\.\S+$/.test(d.email ?? "") ? [] : ["Enter a valid email address."],
next: (d) => (d.accountType === "business" ? "company" : "review"),
},
company: {
id: "company",
validate: (d) => ((d.company ?? "").trim() ? [] : ["Enter your company name."]),
next: () => "review",
},
review: {
id: "review",
validate: () => [],
next: () => null,
},
};
const fieldsByStep: Record<string, string[]> = {
account: ["email", "accountType"],
company: ["company"],
review: [],
};
function computePath(
steps: Record<string, Step>,
startId: string,
data: Data,
): string[] {
const path: string[] = [];
const seen = new Set<string>();
let id: string | null = startId;
while (id !== null) {
if (seen.has(id)) throw new Error(`Flow loops at step "${id}".`);
seen.add(id);
path.push(id);
id = steps[id].next(data);
}
return path;
}The cycle check turns a bad next function, which would otherwise hang the page, into an error you can see in tests.
Build the summary and the payload
The summary and the payload come from the same path, so the user reviews exactly what gets sent. Fields owned by steps that are no longer on the path are dropped.
const labels: Record<string, string> = {
email: "Email",
accountType: "Account type",
company: "Company name",
};
type ReviewRow = { stepId: string; label: string; value: string };
function reviewRows(path: string[], data: Data): ReviewRow[] {
const rows: ReviewRow[] = [];
for (const stepId of path) {
for (const field of fieldsByStep[stepId] ?? []) {
const value = data[field];
if (value !== undefined) {
rows.push({ stepId, label: labels[field] ?? field, value });
}
}
}
return rows;
}
function buildPayload(path: string[], data: Data): Data {
const payload: Data = {};
for (const stepId of path) {
for (const field of fieldsByStep[stepId] ?? []) {
const value = data[field];
if (value !== undefined) payload[field] = value;
}
}
return payload;
}Each row carries its stepId, so the interface can render an "Edit" link next to it. The payload is built in path order, so the same data always serializes the same way. The submitter below relies on that.
Don't build the payload with { ...state.data }. That sends stale branch data to the server, which may reject it or, worse, store it.
Validate the whole path
type StepErrors = Record<string, string[]>;
function validatePath(
steps: Record<string, Step>,
path: string[],
data: Data,
): StepErrors {
const result: StepErrors = {};
for (const id of path) {
const errors = steps[id].validate(data);
if (errors.length > 0) result[id] = errors;
}
return result;
}Run this when the user presses Submit, even if every step passed when the user first saw it. It is cheap, and it guards against any state path you didn't anticipate, such as restored drafts or code that sets data directly.
Editing from the review step
When the user chooses "Edit" on a row, send them to that step. Keep history consistent with the path so Back keeps working: the history for a step is every path step before it.
function goToStep(
state: FlowState,
path: string[],
target: string,
errors: string[],
): FlowState {
const index = path.indexOf(target);
if (index === -1) return state;
return { ...state, current: target, history: path.slice(0, index), errors };
}
function editStep(
state: FlowState,
steps: Record<string, Step>,
startId: string,
target: string,
): FlowState {
const path = computePath(steps, startId, state.data);
return goToStep(state, path, target, []);
}After the edit, the user moves forward with the normal advance function. If the change alters a branch, the next steps follow the new answers and the review shows the new path. You don't need a "return to review" shortcut for correctness. If you add one, still compute the path again instead of trusting the old one.
Submitting safely
Submission is the one action with side effects outside the flow. Four problems come up:
- Double submission. A double-click, an impatient second tap, or the Enter key held down can send the request twice.
- Retries. After a timeout, the user can't tell whether the server received the data.
- Partial failure. The server may reject one field that the client thought was fine.
- Navigation during the request. Back and Edit must not change the data while it is in flight.
The submission moves through a small set of states:
The submitter below handles the first two problems. It returns the same promise while a request is in flight. It also sends an idempotency key, a unique value the server uses to recognize repeats of the same request. The key stays the same for retries of the same payload and changes when the payload changes.
type SubmitResult =
| { ok: true; confirmationId: string }
| { ok: false; message: string; stepErrors?: StepErrors };
type Send = (payload: Data, idempotencyKey: string) => Promise<SubmitResult>;
function createSubmitter(send: Send) {
let inFlight: Promise<SubmitResult> | null = null;
let lastBody = "";
let key = crypto.randomUUID();
return function submit(payload: Data): Promise<SubmitResult> {
if (inFlight) return inFlight;
const body = JSON.stringify(payload);
if (body !== lastBody) {
key = crypto.randomUUID();
lastBody = body;
}
const request = send(payload, key)
.catch(
(): SubmitResult => ({
ok: false,
message: "We couldn't reach the server. Your answers are saved. Try again.",
}),
)
.finally(() => {
inFlight = null;
});
inFlight = request;
return request;
};
}crypto.randomUUID() is available in browsers and in Node 19 and later. The .catch turns network failures into an ordinary failed result, so the caller handles one shape. The client can only make duplicates less likely. The server must enforce the key to make them harmless.
Now tie validation, navigation, and submission together:
async function submitFlow(
state: FlowState,
steps: Record<string, Step>,
startId: string,
submit: (payload: Data) => Promise<SubmitResult>,
): Promise<{ state: FlowState; result: SubmitResult | null }> {
const path = computePath(steps, startId, state.data);
const stepErrors = validatePath(steps, path, state.data);
const firstInvalid = path.find((id) => stepErrors[id] !== undefined);
if (firstInvalid !== undefined) {
const errors = stepErrors[firstInvalid] ?? [];
return { state: goToStep(state, path, firstInvalid, errors), result: null };
}
const result = await submit(buildPayload(path, state.data));
if (result.ok) return { state, result };
const serverErrors = result.stepErrors ?? {};
const firstRejected = path.find((id) => serverErrors[id] !== undefined);
if (firstRejected !== undefined) {
const errors = serverErrors[firstRejected] ?? [];
return { state: goToStep(state, path, firstRejected, errors), result };
}
return { state: { ...state, errors: [result.message] }, result };
}Here is a run with a fake server:
const submit = createSubmitter(async (payload, key) => {
console.log("sending", JSON.stringify(payload), "key", key);
return { ok: true, confirmationId: "C-1001" };
});
const state: FlowState = {
current: "review",
history: ["account", "company"],
data: {
email: "[email protected]",
accountType: "personal",
company: "Old Co", // left over from an earlier "business" answer
},
errors: [],
};
submitFlow(state, steps, "account", submit).then(({ result }) => {
console.log(result); // payload has no "company" field
});The payload contains only email and accountType. The leftover company value is dropped because company is not on the path.
Handling server errors
Server-side validation can disagree with the client. Examples are an email that is already registered or a rule the client doesn't know about. Handle it this way:
- Ask the server to report errors against fields or step ids, so the client can map them to steps.
submitFlowexpectsstepErrorskeyed by step id. - Send the user to the earliest step with an error and show the message there, using the same error display as client-side validation.
- If the error has no step (a 500, a timeout), stay on the review screen and show one message that says what happened and what to do. Keep all the data.
Never clear the form after a failure.
After success
Once the server accepts the request:
- Show a confirmation with the
confirmationIdand the next thing that will happen (an email, a review period). - Delete any saved draft, so a later visit doesn't offer to resume a flow that is already finished.
- Make Back safe. Either reset the flow to a fresh state or replace the review screen with the confirmation, so the user can't submit the same data a second time by accident.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Sending all of `state.data` | Stale branch data reaches the server | Build the payload from the path |
| Trusting earlier per-step validation | Invalid data submitted after edits | Run `validatePath` on Submit |
| Disabling the button only | Enter key or a second tab can still resubmit | Guard in the submit function and use an idempotency key |
| Clearing data on error | The user retypes everything | Keep `data` and return to the failing step |
| Editing from review by resetting `history` to `[]` | Back skips steps | Set `history` to the path before the target |
| Reusing one idempotency key for different data | Server returns the old result for new data | Change the key when the payload changes |
Exercise
A user chooses "business", fills in "Acme", goes back, switches to "personal", and moves forward to the review. What does the review summary show, and what does the payload contain?
Show answer
The path is account, review, because next returns "review" for personal accounts. The summary shows Email and Account type only. The payload contains email and accountType. The company value is still in state.data, but company is not on the path, so reviewRows and buildPayload skip it.
Exercise
The server rejects a submission with stepErrors: { company: ["That company is already registered."] }. Using submitFlow, which step is shown next, and what is in history?
Show answer
The company step is shown with that message in errors. goToStep sets history to the path steps before it, which is ["account"]. Back returns the user to account, and moving forward from company leads to review again.
Exercise
Write a test case, as a plain description, for the double-submit guard in createSubmitter.
Show answer
Create a submitter whose send returns a promise that resolves after a delay and counts its calls. Call submit twice with the same payload before the first promise resolves. Assert that send was called once and that both calls resolved to the same result. Then call submit again with a changed payload after completion and assert that send ran a second time with a different key.