zundo
zundo copied to clipboard
Unable to undo delete operation on array.
@charkour
Adding a simple demo for reproducing the issue.
- Add more than one object in the array.
[{id:1},{id:2},{id:3}] - Remove one object.
[{id:1},{id:2}] - Now perform Undo
Expected result - [{id:1},{id:2},{id:3}]
Actual result -[{id:1},{id:2}]
Hi @indubabu,
Thanks for making the issue! Could you share the code that is calling undo and useStoreWithUndo? Thanks
Hi @charkour , Please find below for the App component.
Array.splice mutates the state directly. Use Array.slice and other immutable array methods.
removeAllBears: () => set((state) => {
// Using slice to create a new array without the last item
// The current array (state.bears) is not modifed
// Instead a shallow copy is made, and new state with new array is returned
const newArray = state.bears.slice(0, -1);
return { bears: newArray };
}),
If you do want to use mutating methods, you should use something like immer. But i wouldn't use this unless you need to do more complex stuff like modifying a value thats deeply nested into multiple objects.