简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM