Why One Changed Requirement Broke the AI-Written List Page
AI can write the page out, so why does it collapse the moment we change a requirement?
A list page that supports search, pagination, and row selection. Click through it with fixed data and nothing looks wrong.
Then a requirement gets added: "Selection must survive page turns, and clear when the filter condition changes."
Things start to get complicated: page two's select-all box is lit while nothing is actually selected; the search results have changed, but the batch-operation button is still holding old data; switching conditions repeatedly ends up displaying the result of the previous query.
These problems don't need a complicated business to appear. The following derivation uses a simplified React list: the first version verifies that each feature works; a requirement change starts to verify whether they work together.
1. "Add batch selection" first adds a set of rules
Suppose the first version only supports selecting on the current page and clears on page turn. That implementation isn't necessarily wrong; it may fully match what was needed at the time.
Now, with persist-across-pages, at least four questions must be answered:
- Two rows are selected on page one, turn to page two — do those two still count as selected?
- Clicking select-all on page two: does it select the current page, or the entire search result set?
- When the filter changes, is the old selection kept or cleared?
- On batch submit, do you use the current page's data, or the IDs of all selected records?
This article adopts an explicit set of conventions: page turns keep the selection; select-all only operates on the current page; a change to the filter clears the selection and returns to page one; batch submission uses all selected IDs.
These conventions decide how the code gets written.
If you only hand "support cross-page selection" to a programming tool, it might retain IDs, or cache the full row objects, or quietly change select-all to select all results. Several of these approaches can produce a page that visibly works, but the business meaning is different.
Where the requirement doesn't say, the code gives an answer too. That answer may not be the one you want.
The problem here can be that the implementation omitted an existing convention, or that the new requirement changed the previous convention. You can't see a problem in the second version and retroactively conclude the first version was definitely wrong.
2. Whether the select-all box lights up can't depend on "whether something is selected"
The pattern below passes a page-one demo easily:
const allChecked = selectedIds.length === rows.length;
Two rows on the current page, select two, the select-all box lights up.
But after a page turn? The two IDs selected on page one are still there, and page two also happens to have two rows. The counts are equal, the box is still lit, but page two may have nothing selected.
Even in an empty list, 0 === 0 counts as all-selected.
It compresses "all current-page rows are selected" into "the two arrays are the same length". In a single-page scenario, this simplification rarely surfaces; across pages, the premise changes.
The correct judgment looks at every ID on the current page:
const selectedSet = new Set(selectedIds);
const selectedOnPage = rows.filter(row => selectedSet.has(row.id)).length;
const allChecked = rows.length > 0 && selectedOnPage === rows.length;
const indeterminate = selectedOnPage > 0 && !allChecked;
Clicking select-all on the current page also only modifies the current page's IDs:
function togglePage(checked: boolean) {
setSelectedIds(previous => {
const next = new Set(previous);
for (const row of rows) {
if (checked) next.add(row.id);
else next.delete(row.id);
}
return [...next];
});
}
Deselecting all on page two doesn't delete page one's selection along with it.
The records in this example use unique, stable string IDs. The batch button's count comes from selectedIds.length, and the submit parameters also come from selectedIds, not derived from the current page's rows.
The current page shows one page of records; the user selects a set of records. They are two different scopes.
If the business later requires "select all records matching the filter conditions", this ID set is no longer enough. That needs another explicit design, for example query conditions plus excluded IDs, supported by a server-side endpoint. You can't just change the label of the select-all button.
3. What's genuinely hard to change is one fact stored in several places
Another common problem is giving every displayed result its own state:
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [selectedCount, setSelectedCount] = useState(0);
const [allChecked, setAllChecked] = useState(false);
const [canSubmit, setCanSubmit] = useState(false);
So every event handler has to remember to sync them all.
Single-row selection syncs once, select-all syncs once, page turn syncs once, filter clear syncs once more. Miss one, and you get "the button shows 3 selected, but the submit parameters only have 2 IDs".
Continuing to fix usually means adding a few more setState calls where they were missed. The visible bug is fixed, but the next requirement change still has to find every sync point.
Under this article's conventions, storing the IDs is enough:
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const selectedCount = selectedIds.length;
const canSubmit = selectedCount > 0;
// The current page's allChecked and indeterminate are computed from rows and selectedIds
The React documentation recommends avoiding redundant and duplicate state, for exactly this reason: they are hard to keep in sync. No need for another state library here, no need to extract a universal Hook. Move the values that can be computed out of state, and you have fewer places that can drift out of sync.
The same judgment applies to the list data.
If all the data lives on the client, the filtered list can be computed from the raw data and the conditions; if an endpoint is already responsible for filtering and pagination, the client should use that query's response. Decide first who owns the filtering, then decide what to store. Don't mix the client-side full list with server-side pagination logic.
4. Changing the filter condition is a complete state change
If the filter's onChange only updates the keyword, the rest of the state won't understand the new requirement on its own:
setKeyword(nextKeyword);
The user was on page eight, switches the condition, the new result set has one page, but the endpoint is still asked for page eight. The screen shows "no data", and the user thinks nothing matches.
If the selected IDs are kept, batch operations may end up carrying records from the previous query.
Following the rules above, the query conditions can be grouped together, and the reset done at the same event entry. The keyword below refers to the condition actually submitted to the query, without distinguishing an input draft from a committed value:
const [query, setQuery] = useState({ keyword: '', page: 1 });
function changeKeyword(keyword: string) {
setQuery(previous => {
if (previous.keyword === keyword) return previous;
return { ...previous, keyword, page: 1 };
});
if (keyword !== query.keyword) setSelectedIds([]);
}
function changePage(page: number) {
setQuery(previous => ({ ...previous, page }));
// Page turns keep selectedIds
}
Pagination and filtering are deliberately separated here, because their effect on the selection differs.
If a "status filter" is added later, check whether it belongs to a condition that changes the result set; if it does, follow the return-to-page-one, clear-selection rule. Don't wait for a bug to show up in some control and patch a clear there.
When the project is small, these few functions are enough. When update entry points multiply and the same rule has to be written repeatedly, consider a reducer. Code organization serves the rules that already exist; there's no need to build a list engine in advance.
5. The last request sent isn't necessarily the last to return
Demowork with fixed data rarely exposes this:
- Query A is sent.
- The user switches conditions; query B is sent.
- B returns first; the page shows the new results.
- A returns later and overwrites the page with the old result.
The filter shows B, but the records come from A. However correct the selection, select-all, and batch operations are, they are operating on the wrong data.
When writing the Effect request by hand, at minimum make a stale request lose the right to update state. The following is standalone request logic; fetchRows is a project-provided API function that returns Promise<Row[]>:
type Row = { id: string; name: string };
const requestKey = JSON.stringify([query.keyword, query.page]);
const [result, setResult] = useState<{
key: string;
rows: Row[];
} | null>(null);
const [error, setError] = useState<{
key: string;
message: string;
} | null>(null);
useEffect(() => {
let ignore = false;
setError(null);
fetchRows(query).then(
rows => {
if (!ignore) setResult({ key: requestKey, rows });
},
() => {
if (!ignore) {
setError({ key: requestKey, message: '列表加载失败,请重试' });
}
},
);
return () => {
ignore = true;
};
}, [query, requestKey]);
const rows = result?.key === requestKey ? result.rows : [];
const currentError = error?.key === requestKey ? error.message : null;
const loading = result?.key !== requestKey && !currentError;
Two different things happen here.
The ignore flag stops the old Effect's success and failure callbacks from updating the current result. The key on the result makes rendering use only the data matching the current query: right after a condition switch, before the new result comes back, the previous page's records aren't treated as current-page records for display and selection.
The UI should show a loading state based on loading, a failure state and retry entry based on currentError, and disable current-page select-all while loading. That JSX is omitted here, and so are caching, refresh, and pagination totals.
ignore doesn't cancel the network transfer. If the API supports AbortSignal, the old request can be cancelled further; when the project already has a request library, prefer its existing query-key, cancellation, and loading-state mechanisms. There is no need to introduce another scheme for this example.
The key point is: only the current query's result can drive the current list's interactions.
6. Verifying is worth writing beforehand more than generating
"Supports filtering, pagination, batch selection" is only a feature list. Writing out the operation sequence is how you know whether the features connect:
| Operation | Result that should be observed |
|---|---|
| Select A on page one, turn to page two, select B | 2 selected; submit includes A and B |
| Both pages have the same count, page two has nothing selected | Page two's select-all box is not lit |
| Select-all on page two, then deselect the current page | A on page one is still selected |
| Switch the filter while on a later page | Returns to page one; selection clears |
| Switch conditions repeatedly so an old request returns late | The old response cannot overwrite the current result |
| Current query fails | Show a failure state; old data is not presented as the new result |
There's no need to enumerate every imagined edge case at once. First verify away the behaviors this requirement change touches, especially the cross-page, cross-condition, cross-request operations.
The change description given to the AI can use these conventions directly:
Support cross-page selection in the existing list. Page turns keep the IDs; select-all only operates on the current page; when the filter changes, return to page one and clear the selection; batch submit uses all selected IDs. Check the select-all logic, duplicate state, and stale response handling; reuse the project's existing request scheme. After finishing, verify per the operation sequence above.
This passage is useful because it makes clear which old behaviors change and which must stay. After writing it you still review the implementation and run the verification; it doesn't automatically guarantee the generated result is correct.
AI can quickly write the first version of a page, and can help fix the second version. But "the page can display" only covers a single moment; "the requirement can keep being changed" also depends on how state transitions between operations.
The next time you hear "add batch selection", settle the cross-page, select-all, and filter-reset sentences first. Otherwise everyone thinks they're adding a button, and what gets added is several sets of mutually conflicting behaviors.
References:
- React: Choosing the State Structure — redundant state, duplicate state, and sync problems.
- React: useEffect — out-of-order responses and the
ignoreexample in cleanup.
Top 2 of 4 from juejin.cn, machine-translated. The original thread is authoritative.
The 0==0 example for the select-all checkbox is painfully real: an empty list counts as all-selected, so a single-page demo never catches it, and the flaw shows the moment you switch pages. On the section about storing the same fact in multiple places, keeping selectedCount in its own state and syncing it in every event — miss one place and the button shows 3 items while submission sends only 2 IDs. Deriving it from selectedIds.length is indeed the least invasive fix. I agree with the comment above about writing the convention into the repo rules. Along that line, I'd like to ask: for the request out-of-order section that uses requestKey comparison, would you also require hooking up AbortSignal in the rules, or is ignore plus key already enough?
Inspired.
The phrase 'where the requirement is unclear, the code will still give an answer' is spot on. Our habit is to write conventions like 'keep selection on pagination, clear it when filters change' into the repo rules that the AI reads from the start, not just into this one requirement ticket. Otherwise, two months later when someone else has the AI modify this list, it will guess again based on its own understanding.
Approved.