feat(store): add hydration logic and state management to new problem store

This commit is contained in:
cfngc4594 2025-04-04 21:13:12 +08:00
parent 54ac7b3cd5
commit 0d074a556d

View File

@ -2,18 +2,34 @@ import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware"; import { createJSONStorage, persist } from "zustand/middleware";
import { ProblemSchema } from "@/components/features/dashboard/admin/problemset/new/schema"; import { ProblemSchema } from "@/components/features/dashboard/admin/problemset/new/schema";
type NewProblemState = Partial<ProblemSchema> & { interface NewProblemActions {
setHydrated: (value: boolean) => void;
setData: (data: Partial<ProblemSchema>) => void; setData: (data: Partial<ProblemSchema>) => void;
}; }
type NewProblemState = Partial<ProblemSchema> & {
hydrated: boolean;
} & NewProblemActions;
export const useNewProblemStore = create<NewProblemState>()( export const useNewProblemStore = create<NewProblemState>()(
persist( persist(
(set) => ({ (set) => ({
hydrated: false,
setHydrated: (value) => set({ hydrated: value }),
setData: (data) => set(data), setData: (data) => set(data),
}), }),
{ {
name: "new-problem-storage", name: "zustand:new-problem",
storage: createJSONStorage(() => localStorage), storage: createJSONStorage(() => localStorage),
// eslint-disable-next-line @typescript-eslint/no-unused-vars
partialize: ({ hydrated, ...rest }) => rest,
onRehydrateStorage: () => (state, error) => {
if (error) {
console.error("An error happened during hydration", error);
} else if (state) {
state.setHydrated(true);
}
},
} }
) )
); );