0

I am retrieving a list of objects and attempting to store them inside a class I have in my Zustand store.

    async function initializeData() {
      const [
        computerGroups,
        {...other vars}
      ] = await Promise.all([
        getComputerGroups()
        {... other api calls}
      ]);

      store.setStoragePolicySettings({
        ...store.storagePolicySettings,
        appliesToOptions: computerGroups,
      });

My store looks as follows:

type store = {
  storagePolicy: StoragePolicyDto;
  setStoragePolicy: (policy: StoragePolicyDto) => void;

  storagePolicySettings: StoragePolicySettings;
  setStoragePolicySettings: (
    storagePolicySettings: StoragePolicySettings
  ) => void;
};

export const useStore = create<store>((set) => ({
  storagePolicy: new StoragePolicyDto(),
  setStoragePolicy(storagePolicy: StoragePolicyDto) {
    set((state) => ({
      ...state,
      storagePolicy: storagePolicy,
    }));
  },
  storagePolicySettings: new StoragePolicySettings(),
  setStoragePolicySettings(storagePolicySettings: StoragePolicySettings) {
    set((state) => ({
      ...state,
      storagePolicySettings: storagePolicySettings
    }));
  },
}));

I do not have an issue when updating something like StoragePolicy, however when I try to update the state of StoragePolicySettings, I am getting undefined.

I am expecting a field inside of the StoragePolicySettings class such as appliesToOptions to be updated, but instead it is just getting undefined. I have logged the data being returned, so I know it is an issue with how the data is being spread into this nested object.

1 Answers1

1

Can't see a reason why this would happen given the code provided.

Since you are always updating the whole state property, you can try without using a callback. So it would look like this:

Instead of:

setStoragePolicySettings(storagePolicySettings: StoragePolicySettings) {
    set((state) => ({
      ...state,
      storagePolicySettings: storagePolicySettings
    }));
  },

Try:

 setStoragePolicySettings(storagePolicySettings: StoragePolicySettings) {
     set({storagePolicySettings: storagePolicySettings});
  }
Mihail Iliev
  • 163
  • 1
  • 8