Search code examples
react-nativezustand

zustand state not resetting


I'm trying to reset my state when pressing a button but for some reason the state just will not reset. I have a similar store elsewhere that do reset and the difference between them is the other store initialState is a nested object but I can't figure out why they behave differently.

slice

    const initialState = {
      selected: [],
    };

    export const createMediaSelectedSlice: StateCreator<SelectedMediaSlice> = (set) => ({
      ...initialState,
      addSelection: (media: ImageProps) =>
        set((state) => ({
          selected: [...state.selected, media],
        })),
      removeSelection: (media: ImageProps) =>
        set((state) => ({
          selected: state.selected.filter(
            (item) => item.digestId !== media.digestId
          ),
        })),
      reset: () => {
        set(initialState);
      },
    });

combined store

    export const useMediaStore = create<SelectedMediaSlice & MediaViewSlice>((...a) => ({
    ...createMediaSelectedSlice(...a),
    ...createMediaViewSlice(...a),
      })
    );

button

    const reset = useMediaStore((state) => state.reset);
    const handlePress = () => {
        reset();
    }

Solution

  • My guess, I could be wrong, is that both of your stores have a "reset" button (assuming). If that is the case, you are merging both stores together, and one of those "resets" will be overwritting. They share a namespace. Rename the reset. ala

        export const createMediaSelectedSlice: StateCreator<SelectedMediaSlice> = (set) => ({
          ...initialState,
          addSelection: (media: ImageProps) =>
            set((state) => ({
              selected: [...state.selected, media],
            })),
          removeSelection: (media: ImageProps) =>
            set((state) => ({
              selected: state.selected.filter(
                (item) => item.digestId !== media.digestId
              ),
            })),
          resetMedia: () => {
            set(initialState);
          },
        });
    
    
    and use like:
    
        const reset = useMediaStore((state) => state.resetMedia);
        const handlePress = () => {
            reset();
        }