Sub topic 4
Moving forward and back
This chapter covers navigation in a guided flow. It assumes you have read the chapters on step design and flow state, and that you can read TypeScript. You should know what a Step and a FlowState are. The code uses the same types as earlier chapters, so it runs without a framework.
By the end you should be able to explain why forward navigation needs validation and back navigation does not. You should also be able to say why a history stack beats a numeric step index when the path branches.
Two moves with different rules
A flow has two basic moves.
- Forward commits the current step. It checks the user's input, picks the next step, and records where the user came from.
- Back undoes the last forward move. It does not check anything and returns to the step the user actually visited.
The two moves are not mirror images. Forward is gated by validation. Back must never be gated, because a user who is stuck on a step with an error needs a way out. If Back required valid input, a user who realizes they chose the wrong account type could not go back and fix it.
| Move | Validates current step? | Changes history | Changes collected data |
|---|---|---|---|
| Forward (valid) | Yes | Pushes current step id | No (the form writes data as the user types) |
| Forward (invalid) | Yes | No | No |
| Back | No | Pops the last id | No |
Navigation functions never delete answers. Only the form inputs and later cleanup logic touch data.
The state that navigation needs
Navigation depends on three fields of FlowState. current is the id of the step on screen. history is the list of step ids the user has left and could return to. errors holds the messages from the last failed attempt to advance.
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[];
};Each step says where it leads through next. The flow does not store a list of steps in order. It stores the steps by id, and each step computes its successor from the collected data. That makes branching a property of the step.
Moving forward
The forward function does three things in a fixed order: validate, choose the next step, record history.
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: [],
};
}Four details matter here.
- Validation runs first. If it fails, the function returns the same step with the error list.
currentandhistorystay unchanged, so a failed attempt leaves no trace in the navigation record. nextruns only after validation passes. A step'snextmay read fields that are only meaningful when they are valid. Calling it earlier risks routing on bad input.- History receives the step being left, not the new one. After moving from
accounttocompany,historyis["account"]andcurrentis"company". The current step is never in its own history. - Errors are cleared on success. Otherwise the messages from step one would appear on step two.
A null from next marks the last step. This function treats that as "nothing to advance to" and stays put. Submission is a separate action, covered in the review chapter. Keeping it out of advance means a double click on Next cannot submit twice.
Moving back
Back is shorter because it has no decisions to make.
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 function reads the top of the stack, makes it current, and removes it from the stack. On the first step the history is empty, so it returns the state unchanged. Your UI should also hide or disable the Back button in that case, but the function stays safe if it is called anyway.
Back clears errors because those messages belonged to the step the user just left. It keeps data untouched. When the user returns to a step, the form should show what they typed before.
Why a history stack and not a step number
A simple wizard keeps an integer such as stepIndex and uses stepIndex + 1 and stepIndex - 1. That works only when every user sees every step in the same order. Once a flow branches, it breaks.
Take the flow from the earlier chapters. A business account goes account → company → review. A personal account goes account → review. If Back used stepIndex - 1, a personal user on review would be sent to company, a step they never saw.
The history stack records the path actually taken, so Back follows it exactly.
The dashed arrow out of review has two possible targets. Which one applies depends on the user's path, and only history holds that information.
Changing an answer and walking a different path
The trickiest case is a user who goes back and changes an answer that controls a branch. Follow it with the history stack.
- The user picks "business" and reaches
company. State:current = "company",history = ["account"]. - The user clicks Back. State:
current = "account",history = []. - The user changes the type to "personal" and clicks Next.
nextnow returns"review". State:current = "review",history = ["account"].
Back popped account off the stack, and the later advance call computed a fresh path. The abandoned company step is not in the history, so no stale route remains. This works because back removes entries instead of only moving a pointer.
One problem remains. The company field is still in data, because navigation does not delete answers. If the final payload is built from all of data, a personal account is submitted with a company name. There are two common fixes.
- Prune at submit time. Rebuild the payload from only the steps on the final path.
- Prune when a branch changes. Remove the answers of steps that are no longer reachable.
Pruning at submit time is safer, because a user who flips back to "business" finds their company name still there. Here is a helper that computes the path from the data, which also gives you a list of steps to check before submitting.
function pathFrom(
startId: string,
data: Data,
steps: Record<string, Step>
): string[] {
const path: string[] = [];
const seen = new Set<string>();
let id: string | null = startId;
while (id !== null && !seen.has(id)) {
seen.add(id);
path.push(id);
id = steps[id].next(data);
}
return path;
}The seen set stops the loop if a mistake in next creates a cycle. A cycle would otherwise hang the page.
Running it
This block combines the earlier pieces into a script you can run with a TypeScript runner such as npx tsx flow.ts. It uses the steps map from the Topic Spine's first example.
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,
},
};
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: [],
};
}
let state: FlowState = {
current: "account",
history: [],
data: { email: "[email protected]", accountType: "business" },
errors: [],
};
state = advance(state, steps);
console.log(state.current, state.history); // company [ 'account' ]
state = advance(state, steps); // company name is empty
console.log(state.current, state.errors); // company [ 'Enter your company name.' ]
state = { ...state, data: { ...state.data, company: "Acme" } };
state = advance(state, steps);
console.log(state.current, state.history); // review [ 'account', 'company' ]
state = back(back(state));
console.log(state.current, state.history); // account []
state = back(state); // already at the start
console.log(state.current, state.history); // account []The second call shows the gate working. The company name is missing, so the state stays on company and carries one error. The last call shows that Back on the first step does nothing.
Common errors
- Validating on Back. This traps users on a step with a bad value. Validate only on forward moves.
- Pushing the destination onto history. Then Back lands on the step the user is already viewing, and the first click appears to do nothing.
- Recomputing the previous step from data. You could ask each step for a
previousfunction, but that can disagree with what the user did, for example after they edit an answer. The stack records what happened. Prefer it. - Mutating state in place. Both functions return new objects. If you call
history.pushon the existing array, UI frameworks that compare by reference will not re-render, and stored snapshots will change after the fact. - Leaving
errorsin place on Back. Old messages then show up on a step that never produced them. - Letting the browser Back button leave the flow. In a web app, one click on the browser's Back button usually leaves the whole wizard. If you want it to act like your Back button, push a browser history entry for each step and call
backwhen the browser reports a pop. That mapping is part of the persistence and accessibility chapters.
Testing the moves
Because advance and back are pure functions, you can test them without rendering anything. Check these properties for every flow.
- Forward with invalid data leaves
currentandhistoryunchanged and fillserrors. - Forward with valid data adds exactly one entry to
history. back(advance(s))returns to the originalcurrentandhistory, wheneveradvancesucceeded.- Back on an empty history returns the same state.
- After changing a branching answer and moving forward,
historycontains only steps on the new path.
The third property is a good round-trip check. If it fails, one of the two functions is recording history incorrectly.
Summary of rules
- Forward validates, then routes, then records the step it left.
- Back never validates, never touches
data, and removes one history entry. - History is a stack of visited steps, not a counter.
- Failed attempts change only
errors. - Stale answers from abandoned branches are removed when you build the payload.
Exercise
A user is on review with history = ["account", "company"]. They click Back once, go to account, change the account type from "business" to "personal", and click Next. What are current and history after that? What happens to the company value in data, and where should you remove it?
Show answer
After one Back, current is "company" and history is ["account"]. The user then needs a second Back to reach account, which leaves history as []. After they change the type to "personal" and click Next, next returns "review", so current is "review" and history is ["account"]. The company value is still in data because navigation never deletes answers. Remove it when you build the submitted payload, by keeping only the answers for steps returned by pathFrom("account", data, steps). Deleting it earlier would lose the user's input if they switch back to "business".
Exercise
A teammate replaces the history stack with stepIndex, using stepIndex - 1 for Back. Describe one concrete sequence of clicks in the account flow where this sends the user to a step they never saw.
Show answer
A user chooses "personal" on account and clicks Next, going straight to review. If steps are ordered account, company, review, review has index 2. Back computes index 1, which is company, a step the personal user skipped. The history stack avoids this because review was reached from account, so Back returns to account.