I have zustand stores created using Car ID, and I needed the function to easily reset these stores (dozens at once). I was looking through the web for possible solutions and found one, but its very hard for me to type it, here is the function itself:
const resetSet = new Set();
export const resettable = (create: any) => (initialState: any) => {
const useStore = create(() => initialState);
const reset = () => useStore.setState(initialState, true);
resetSet.add(reset);
return useStore;
};
export const resetAll = () => resetSet.forEach((reset: any) => reset());
And the example usage:
export type CarsState = {
carInfo: CarInfoType | null;
setCarInfo: (carInfo: CarInfoType | null) => void;
...etc.
}
export const useCarState = (carID: string) =>
resettable(
create<CarState>()(
persist(immer(handler), {
name: `carState-${carID}`,
storage: createJSONStorage(() => sessionStorage),
}),
),
);
I tried several things, but for example here I cannot type useStore hook arguments properly:
import { StateCreator } from 'zustand';
type CreateFunction = <StateType>(initializer: () => StateType) => StateCreator<StateType>;
type ResettableFunction = <T>(create: CreateFunction) => (initialState: T) => StateCreator<T>;
const resetSet = new Set<() => void>();
export const resettable: ResettableFunction = <T>(create: CreateFunction) => (initialState: T) => {
const useStore = create(() => initialState);
const reset = () => useStore(initialState, true);
resetSet.add(reset);
return useStore;
};