Search code examples
javascriptreactjsnext.jszustand

Next.js Zustand dynamic key addition to a state not working


I have been trying to add a key to a state dynamically in zustand. I have tried multiple ways like

1.

const store = (set, get) => ({
  keyAttrib: {key1: "value1", key2: 2},
  update: (key, value) => {
    let newState = { ...get().keyAttrib, [key]: value };
    set(newState);
  }
})
  1.   const store = (set) => ({
        keyAttrib: { key1: "value1", key2: 2 },
        update: (key, value) => {
          set((state) => ({ keyAttrib: { ...state.keyAttrib, [key]: value } }));
        },
      });
    

but none of them seem to be working.


Solution

  • The second example you provided works perfectly fine for me:

     const useStore = create((set) => ({
        keyAttrib: {key1: "value1", key2: 2},
        update: (key, value) =>
        set((state) => ({
          keyAttrib: {
                ...state.keyAttrib,
                [key]: value,
            },
        })),
      }));
    

    Here's the working codesandbox (please ignore any styling) where you can add/update key-value pairs, the dropdown will always update key3. If this is still not helping, please provide a minimal wokring example on codesandbox.

    event.preventDefault() is needed to prevent the form from performing a page refresh which will reset your Zustand Store with its initial value.