charkour / zundo

🍜 undo/redo middleware for zustand. <700 bytes
https://codesandbox.io/s/zundo-2dom9
MIT License
616 stars 20 forks source link

Unable to undo delete operation on array. #161

Open indubabu opened 8 months ago

indubabu commented 8 months ago

@charkour

Adding a simple demo for reproducing the issue.

  1. Add more than one object in the array. [{id:1},{id:2},{id:3}]
  2. Remove one object. [{id:1},{id:2}]
  3. Now perform Undo

Expected result -[{id:1},{id:2},{id:3}]

Actual result -[{id:1},{id:2}] image

charkour commented 8 months ago

Hi @indubabu,

Thanks for making the issue! Could you share the code that is calling undo and useStoreWithUndo? Thanks

indubabu commented 8 months ago

Hi @charkour , Please find below for the App component. image

alexanderhorner commented 7 months ago

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.