zundo icon indicating copy to clipboard operation
zundo copied to clipboard

Updating state with immer doesnt work

Open yarinsa opened this issue 5 months ago • 3 comments

Hey, I am using Immer as middleware, Ideally I wouldn't have to use 'handleSet' at all, But assuming I have to to get access to Immer 'draft', seems like the draft is not propagated to the handle set What approach should I do here? And maybe there is a workaround I can apply? I tried the following setup:

export const useBoundStore = createWithEqualityFn<BoundStore>()(
  temporal(
    immer((...args) => {
      return {
        ...createGraphSlice(...args),
        ...createSelectedSlice(...args),
        ...createGlobalSlice(...args),
      };
    }),
    {
      handleSet: (handleSet) => {
        return throttle<typeof handleSet>((state: BoundStore) => {
          console.info('handleSet called');
          handleSet(draft => {
            state.nodesLookup.forEach((node, id) => {
              if (!state.nodesLookup.has(id)) {
                draft.nodesLookup.delete(id);
              }
              else {
                draft.nodesLookup.set(id, node);
              }
            })
            return draft;

          });
        }, 1000);
      },
    },
  ),
  shallow,
);

Screenshot 2024-01-21 at 18 59 46

yarinsa avatar Jan 21 '24 16:01 yarinsa

Hey!

Just to clarify, what are you trying to achieve? Are you trying to modify your zustand store state within handleSet? If so, I'm not sure this is the appropriate place to modify zustand store state, as I believe handleSet is used for determining when zundo should add to its state history within the temporal state attached to your zustand store.

See this example of zundo with immer: https://codesandbox.io/p/sandbox/zustand-with-zundo-and-immer-489pty?file=%2Fsrc%2FApp.tsx%3A26%2C23

pstrassmann avatar Jan 21 '24 17:01 pstrassmann

Hey!

Just to clarify, what are you trying to achieve? Are you trying to modify your zustand store state within handleSet? If so, I'm not sure this is the appropriate place to modify zustand store state, as I believe handleSet is used for determining when zundo should add to its state history within the temporal state attached to your zustand store.

See this example of zundo with immer: codesandbox.io/p/sandbox/zustand-with-zundo-and-immer-489pty?file=%2Fsrc%2FApp.tsx%3A26%2C23

Thanks Iv'e looked into the example and seems like I got it right in the first time :) But... It still doesn't work, going to debug deeper and hopefully find a solution.

I am afraid that it doesn't update my "Map" objects

    nodes: [],
    edges: [],
    nodesLookup: new Map(),
    edgesLookup: new Map(),
    getNodes: () => {
      return Array.from(get().nodesLookup.values());
    },
    getEdges: () => {
      return Array.from(get().edgesLookup.values());
    },

yarinsa avatar Jan 22 '24 08:01 yarinsa

@yarinsa,

Could you provide a reproduction of the error?

charkour avatar Mar 10 '24 03:03 charkour