charkour / zundo

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

undo function don't work properly with nested objects #159

Closed frascavone closed 8 months ago

frascavone commented 8 months ago

As the title says, if I add a deep nested object to the currentState and then execute undo function, pastState array is populated, but currentState remains the same. Here's an example: https://codesandbox.io/p/sandbox/zundo-deep-equal-forked-dx37sj?file=%2Fsrc%2FApp.tsx

Can't figure out the reason, maybe it's too nested?

pstrassmann commented 8 months ago

Hi @frascavone!

I believe you are writing your zustand state setter in a malformed way, and that is causing the problem. See this sandbox with your issue fixed: https://codesandbox.io/p/sandbox/frascavone-sandbox-xxlmf4?file=%2Fsrc%2FApp.tsx

I just replaced your addProduct state setter with this:

    addProduct: () =>
      set((state) => {
        const updatedMenus = structuredClone(state.menus);

        updatedMenus[0].categories[0].products = [
          ...state.menus[0].categories[0].products,
          {
            id: "taMovpUX0jivRYGZwgwv",
          },
        ];

        return {
          ...state,
          menus: updatedMenus,
        };
      }),
frascavone commented 8 months ago

Hi @frascavone!

I believe you are writing your zustand state setter in a malformed way, and that is causing the problem. See this sandbox with your issue fixed: https://codesandbox.io/p/sandbox/frascavone-sandbox-xxlmf4?file=%2Fsrc%2FApp.tsx

I just replaced your addProduct state setter with this:

    addProduct: () =>
      set((state) => {
        const updatedMenus = structuredClone(state.menus);

        updatedMenus[0].categories[0].products = [
          ...state.menus[0].categories[0].products,
          {
            id: "taMovpUX0jivRYGZwgwv",
          },
        ];

        return {
          ...state,
          menus: updatedMenus,
        };
      }),

Thanks!! this solved my issue, really appreciate the quick and good answer. Cheers ;)