Sub topic 7
Branching on Earlier Answers
This chapter assumes you can read TypeScript and have followed the earlier chapters on flow state and navigation. You should know the FlowState shape (current step, history, data, errors) and how advance and back work.
Why branching belongs in data
Some questions only matter for some users. A business account needs a company name. A personal account does not. You could write if (accountType === "business") inside your navigation code, but those checks spread quickly. After a few branches, no one can tell which steps a user will see.
A better approach is to give each step a next function. The function reads the collected data and returns the id of the following step, or null when the flow ends. The branching rules then sit next to the step that asks the question.
type Data = Record<string, string>;
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
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,
},
};The account step sends business users to company and everyone else straight to review. Both paths meet again at review.
How navigation uses the branch
The advance function from the navigation chapter needs no changes. It validates the current step, asks the step for the next id, and pushes the current id onto history.
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
function advance(state: FlowState, steps: Record<string, Step>): FlowState {
const step = steps[state.current];
const errors = step.validate(state.data);
if (errors.length > 0) return { ...state, errors };
const nextId = step.next(state.data);
if (nextId === null) return { ...state, errors: [] };
return {
...state,
current: nextId,
history: [...state.history, state.current],
errors: [],
};
}
function back(state: FlowState): FlowState {
const previous = state.history[state.history.length - 1];
if (previous === undefined) return state;
return {
...state,
current: previous,
history: state.history.slice(0, -1),
errors: [],
};
}The history stack is what makes back correct after a branch. A user who skipped company presses Back from review and lands on account, because that is the step they actually came from. If back computed "the step before this one in a list", it would show a step the user never saw.
Common errors
Stale answers from an abandoned branch
Suppose a user picks "business", enters a company name, goes back, and switches to "personal". The company value is still in data. If you submit all of data, you send a company name for a personal account.
Fix this at one of two points:
- Clear fields owned by a step when the answer that unlocked it changes.
- Build the submitted payload only from the steps in
historyplus the current step. This is safer, because it cannot go out of date.
Branch conditions that read missing data
d.accountType === "business" is false when accountType is undefined. Here that sends the user to review, which may be wrong. Validate the answer that controls a branch in the same step that asks for it. In the account example, add a check that accountType is one of the allowed values. Then next only runs on data you have checked.
Branches that never rejoin or loop
Every path should end at a step whose next returns null. Two steps that return each other's ids create a loop that validation will not catch. Walk the graph from the first step in a test and confirm that each path terminates. Chapter 12 covers this.
Changing an answer after Back
When a user goes back and changes the controlling answer, the steps ahead of them may differ from the ones they already completed. The history entries after the changed step are discarded, because back removes them as the user moves. Moving forward again rebuilds the path from the new answer.
Progress with branches
Branches change how many steps remain, so a fixed "Step 2 of 3" can later become "Step 3 of 4". The progress chapter covers this. For now, a label that shows only the current step number avoids the contradiction.
function progressLabel(state: FlowState): string {
return "Step " + (state.history.length + 1);
}Exercise
A user chooses "business", fills in the company step, presses Back twice, and changes the account type to "personal". They then reach the review step. Which company-related problem can occur on submission, and what are two ways to prevent it?
Show answer
The old company value is still in data, so a personal account could be submitted with a company name. Prevent it by clearing the company field when the account type changes, or by building the payload only from steps on the current path (history plus the current step).