The Cancel Button That Didn't: Why Modal Edits Leak Into Your List
theme: cyanosis highlight: atom-one-dark
There is an "Edit" button in the list. Click it to open a modal, change the name from "Xiao Wang" to "Xiao Li", then click Cancel.
The modal closes, but the list already shows "Xiao Li". Sometimes nothing changes immediately, and only after you interact with the page does the new name suddenly appear.
Start this kind of problem by checking one spot: is the form directly mutating the object from the list?
Canceling only closes the modal, it doesn't undo changes
Here's a simplified React form. When the editor opens, it puts the selected record into the form:
function openEditor(row) {
setForm(row);
setOpen(true);
}
The input updates the name:
function changeName(name) {
form.name = name;
setForm({ ...form });
}
Cancel closes the modal:
function cancel() {
setOpen(false);
}
The problem is in the first snippet. setForm(row) doesn't copy the data. After it opens, the form and that record in the list point to the same object.
Executing form.name = name also modifies the record in the list.
The following setForm({ ...form }) creates a new object, but the original one has already been changed by the previous line. The Cancel button closes the modal, but it can't restore the data automatically.
This also explains why sometimes “it doesn't change right after cancel, only later”: mutating the object directly doesn't notify React to update the list, so the next time the list re-renders, it reads the mutated data. The UI not showing the change temporarily doesn't mean the data wasn't touched.
Give the form its own copy first
If the record only has simple fields like name and email, you can copy it when opening:
function openEditor(row) {
setForm({ ...row });
setOpen(true);
}
Also create new objects during input, instead of directly mutating the old one:
function changeName(name) {
setForm(previous => ({
...previous,
name,
}));
}
Now the editor modifies a copy in the form. The record in the list stays untouched until the user clicks Save.
Cancel just needs to discard this form data:
function cancel() {
setOpen(false);
setForm(null);
}
These are handler fragments. The actual page needs to render the input only when form exists, to avoid reading empty values after closing.
Spread operator added, still leaking?
When the record contains nested objects, copying only the outer layer isn't enough:
const row = {
id: 'u1',
name: 'Xiao Wang',
address: { city: 'Hangzhou' },
};
const form = { ...row };
form.address.city = 'Shanghai';
console.log(row.address.city); // Shanghai
form is a new object, but form.address and row.address still point to the same address object.
You've changed the outer box, but the inner contents are still shared.
At this point, you can build the form field by field. For example, if the modal only edits the name and city, just take the needed fields:
function openEditor(row) {
setForm({
id: row.id,
name: row.name,
city: row.address.city,
});
setOpen(true);
}
The form doesn't have to look like the data returned by the API. If you store the city as a string, the input doesn't need to touch the address object in the list.
If you really need to preserve the nested structure, you must copy the address object together when updating the city:
setForm(previous => ({
...previous,
address: {
...previous.address,
city: nextCity,
},
}));
This snippet assumes the form already has address. It doesn't automatically deep-copy all nested objects: whichever layer you modify, check whether that layer still mutates the old object.
You could also use structuredClone(row) for data that supports structured cloning. But functions can't be cloned that way, and class instance prototypes won't be preserved as-is. For ordinary edit forms, explicitly picking out the needed fields is usually easier to maintain.
Update the list only when Save is clicked
With the form independent, the Save step remains.
Assume the project already has an updateUser API function that takes the ID, name, and city from the form and returns the updated full record. Below, the loading state is omitted and we look at when data is written back to the list:
async function save() {
try {
const saved = await updateUser(form);
setRows(previous => previous.map(
row => row.id === saved.id ? saved : row
));
setOpen(false);
setForm(null);
} catch {
setError('Save failed, please retry');
}
}
On successful request, replace the old record in the list with the server-returned record, then close the modal. On failure, keep the user's input so they can retry.
The actual UI should also show errors and disable Save, Cancel, and inputs while the request is in progress. Otherwise, the request has already been sent, the user clicks Cancel, the server may still save successfully, and it's unclear what “cancel” actually cancels. Also clear the previous error message before each save attempt.
Some products update the UI first and then send the request, which is optimistic updating. That requires separate handling for failure rollback. For ordinary backend edit forms, without real-time feedback requirements, waiting for a successful save first makes behavior easier to describe.
Don't add a "restore old value" to the Cancel button first
When hitting this bug, it's tempting to remember the original name and write it back on Cancel.
The name gets fixed. Then later you add city, tags, contacts, and you keep having to add restore logic. Missing one field brings the problem back.
A more direct approach is to make the editing process never modify the list in the first place. Cancel is responsible for closing and discarding; Save is responsible for committing and updating.
During verification, try these steps:
- Change the name, then cancel: the list keeps the original value.
- Change a nested field, then cancel: the list also keeps the original value.
- Open the same record again and see the saved content.
- Save fails: input is still there; save succeeds: the list updates.
If an edit modal has a “cancel doesn't work” problem, look for setForm(row) first, then for form.xxx = .... These two places often connect the issue: the window closes, but what's changed is the object in the list.
Reference: React: Updating Objects in State
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
Building the form field-by-field is indeed the most stable, but the cost is that it becomes a manually maintained checklist: every time you add an editable field, you have to touch two places—copy it when opening and reassemble it when saving. Miss one spot and this bug recurs. If someone on the team cuts corners and goes straight to deep copy, first be clear about the respective costs. JSON round-trip turns dates into strings, keys with value undefined disappear entirely, NaN and Infinity become null. The browser's native structuredClone throws DataCloneError on functions, DOM nodes, and class instances, and the cloned class instances are just plain objects—methods are gone. Date fields blow up first: they come in as Date, deep copy turns them into strings, and calling toISOString() again before submission yields a TypeError, completely white-screening the UI. Let me add a fifth check to your four: for the same record, open the edit twice in a row—first change and cancel, then second time open and see if the value you get is the one you just edited. If the editor is a child component using useState(props.row) to receive data, the second time it opens, it still has the first copy.
A flash of insight