diff --git a/src/app/create/[id]/page.tsx b/src/app/create/[id]/page.tsx index d74b7fc..c8555cc 100644 --- a/src/app/create/[id]/page.tsx +++ b/src/app/create/[id]/page.tsx @@ -48,6 +48,7 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => { file, setFile, blueprint, + hasHydrated: storeHasHydrated, } = store; const [errors, setErrors] = useState([]); @@ -118,7 +119,13 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => { }, [savedEmls[id]]); // Load data if an id is provided + // Wait for store hydration before resetting to prevent race condition + // where hydrated state overwrites the reset state useEffect(() => { + if (!storeHasHydrated) { + return; + } + if (id === 'new') { reset(); setHasLoadedBlueprint(false); @@ -140,7 +147,7 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => { }; loadBlueprint(); } - }, [id]); // Only run when id changes, not on step changes + }, [id, storeHasHydrated]); // Run when id or hydration state changes useEffect(() => { // Load all EMLs from IndexedDB on mount @@ -444,8 +451,8 @@ const CreateBlueprint = ({ params }: { params: Promise<{ id: string }> }) => { return <>; }; - // Show loader while auth store is hydrating from localStorage - if (!hasHydrated) { + // Show loader while auth store or create blueprint store is hydrating from storage + if (!hasHydrated || !storeHasHydrated) { return (
diff --git a/src/app/create/[id]/store.ts b/src/app/create/[id]/store.ts index f474c35..7a5af7b 100644 --- a/src/app/create/[id]/store.ts +++ b/src/app/create/[id]/store.ts @@ -25,6 +25,8 @@ interface ExtendedBlueprintProps extends BlueprintProps { type CreateBlueprintState = ExtendedBlueprintProps & { blueprint: Blueprint | null; validationErrors: ValidationErrors; + hasHydrated: boolean; + setHasHydrated: (value: boolean) => void; setField: (field: keyof ExtendedBlueprintProps, value: any) => void; validateField: (field: keyof BlueprintProps) => void; validateAll: () => boolean; @@ -76,6 +78,8 @@ export const useCreateBlueprintStore = create()( blueprint: null, validationErrors: {}, file: null, + hasHydrated: false, + setHasHydrated: (value: boolean) => set({ hasHydrated: value }), setField: (field: keyof ExtendedBlueprintProps, value: any) => { set({ [field]: value }); @@ -335,9 +339,17 @@ export const useCreateBlueprintStore = create()( name: 'create-blueprint', // Exclude 'file' from persistence as File objects cannot be serialized partialize: (state) => { - const { file, blueprint, ...rest } = state; + const { file, blueprint, hasHydrated, setHasHydrated, ...rest } = state; return rest; }, + onRehydrateStorage: () => (state) => { + // This is called after the store has been rehydrated from storage + if (state) { + state.setHasHydrated(true); + } else { + useCreateBlueprintStore.setState({ hasHydrated: true }); + } + }, storage: { getItem: async (name) => { const value = await get(name);