How to provide an undo function? #12485
Replies: 1 comment
-
It seems the mistake was on my side. I thought using concat und filter was a sufficient deep clone of the form state, however it was not. I modiefied my setHistory call to use structedClone for complete deep copy: // safe to history (structuredClone needed!)
setHistory((prevState) =>
[structuredClone(props.getValues())]
.concat(structuredClone(prevState))
.filter((_el, index) => index < 20),
); This is most likely overkill and not a perfect solution but it works 😅 Second modification was to remove the first two elements when performing undo, because the resettet state causes a history update and will be added automatically again as current state. // Undo last change
const undo = () => {
// we need at least 2 elements (first is always current state)
if (history.length >= 2) {
const restoreState = structuredClone(history[1]);
// remove current and last state from history
// (last state will be added after reset again as current state)
setHistory((prevState) => prevState.slice(2));
// reset form
props.reset(restoreState);
} else {
toaster.create({
title: "Undo nicht verfügbar",
description: "Es ist keine Historie vorhanden",
type: "warning",
duration: 5000,
});
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi guys,
I have a large, dynamic form and want to provide an undo function for the user.
My idea was to subscribe to any changes of the form, save to an history array und use the reset function to revert the last modification.
However there are multiple problem and I cant get it to work properly.
My undo hook looks like following:
The timeout is used to wait until the user has finished typing and then update the state once (otherwise the whole form will lag badly).
Problem
The undo function is not doing an undo.
The page rerenders, however it shows the same values and I do not understand why this happens..
Initial state:
Changing value:
Console confirmation:
After pressing undo (page has rerendered):
--> Still the same. Pressing undo again doesnt change anything.
Has anyone an idea how to fix this or has a working solution for undo functionality?
Thanks all!
Beta Was this translation helpful? Give feedback.
All reactions