Files
ColaFlow-Web/components/epics/epic-form.tsx
Yaojia Wang be69325797 fix(frontend): Fix Zustand authStore hydration timing issue
Fix race condition where Epic form checked user authentication before
Zustand persist middleware completed hydration from localStorage.

Root cause:
- authStore uses persist middleware to restore from localStorage
- Hydration is asynchronous
- Epic form checked user state before hydration completed
- Result: "User not authenticated" error on page refresh

Changes:
- Add isHydrated state to authStore interface
- Add onRehydrateStorage callback to track hydration completion
- Update epic-form to check isHydrated before checking user
- Disable submit button until hydration completes
- Show "Loading..." button text during hydration
- Improve error messages for better UX
- Add console logging to track hydration process

Testing:
- Page refresh should now wait for hydration
- Epic form correctly identifies logged-in users
- Submit button disabled until auth state ready
- Clear user feedback during loading state

Fixes: Epic creation "User not authenticated" error on refresh

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-05 20:56:13 +01:00

259 lines
8.0 KiB
TypeScript

'use client';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { Button } from '@/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useCreateEpic, useUpdateEpic } from '@/lib/hooks/use-epics';
import type { Epic, WorkItemPriority } from '@/types/project';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { useAuthStore } from '@/stores/authStore';
const epicSchema = z.object({
name: z
.string()
.min(1, 'Title is required')
.max(200, 'Title must be less than 200 characters'),
description: z
.string()
.max(2000, 'Description must be less than 2000 characters')
.optional(),
priority: z.enum(['Low', 'Medium', 'High', 'Critical']),
estimatedHours: z
.number()
.min(0, 'Estimated hours must be positive')
.optional()
.or(z.literal('')),
});
type EpicFormValues = z.infer<typeof epicSchema>;
interface EpicFormProps {
projectId: string;
epic?: Epic;
onSuccess?: () => void;
onCancel?: () => void;
}
export function EpicForm({ projectId, epic, onSuccess, onCancel }: EpicFormProps) {
const isEditing = !!epic;
const createEpic = useCreateEpic();
const updateEpic = useUpdateEpic();
const user = useAuthStore((state) => state.user);
const isHydrated = useAuthStore((state) => state.isHydrated);
const form = useForm<EpicFormValues>({
resolver: zodResolver(epicSchema),
defaultValues: {
name: epic?.name || '', // Fixed: use 'name' instead of 'title'
description: epic?.description || '',
priority: epic?.priority || 'Medium',
estimatedHours: epic?.estimatedHours || ('' as any),
},
});
async function onSubmit(data: EpicFormValues) {
console.log('[EpicForm] onSubmit triggered', { data, user: user?.id, projectId, isHydrated });
try {
// Check if auth store has completed hydration
if (!isHydrated) {
console.warn('[EpicForm] Auth store not hydrated yet, waiting...');
toast.error('Loading user information, please try again in a moment');
return;
}
if (!user?.id) {
console.error('[EpicForm] User not authenticated');
toast.error('Please log in to create an epic');
return;
}
const payload = {
...data,
estimatedHours: data.estimatedHours || undefined,
};
console.log('[EpicForm] Prepared payload', payload);
if (isEditing) {
console.log('[EpicForm] Updating epic', { epicId: epic.id });
await updateEpic.mutateAsync({
id: epic.id,
data: payload,
});
console.log('[EpicForm] Epic updated successfully');
} else {
console.log('[EpicForm] Creating epic', { projectId, createdBy: user.id });
const result = await createEpic.mutateAsync({
projectId,
createdBy: user.id,
...payload,
});
console.log('[EpicForm] Epic created successfully', result);
}
console.log('[EpicForm] Calling onSuccess callback');
onSuccess?.();
} catch (error) {
console.error('[EpicForm] Operation failed', error);
const message = error instanceof Error ? error.message : 'Operation failed';
toast.error(message);
}
}
const isLoading = createEpic.isPending || updateEpic.isPending;
const priorityOptions: Array<{ value: WorkItemPriority; label: string; color: string }> = [
{ value: 'Low', label: 'Low', color: 'text-blue-600' },
{ value: 'Medium', label: 'Medium', color: 'text-yellow-600' },
{ value: 'High', label: 'High', color: 'text-orange-600' },
{ value: 'Critical', label: 'Critical', color: 'text-red-600' },
];
return (
<Form {...form}>
<form
onSubmit={(e) => {
console.log('[EpicForm] Form submit event triggered', {
formState: form.formState,
values: form.getValues(),
errors: form.formState.errors,
});
form.handleSubmit(onSubmit)(e);
}}
className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Epic Title *</FormLabel>
<FormControl>
<Input placeholder="e.g., User Authentication System" {...field} />
</FormControl>
<FormDescription>
A concise title describing this epic
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="description"
render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea
placeholder="Detailed description of the epic, including goals and acceptance criteria..."
className="resize-none"
rows={6}
{...field}
/>
</FormControl>
<FormDescription>
Optional detailed description (max 2000 characters)
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField
control={form.control}
name="priority"
render={({ field }) => (
<FormItem>
<FormLabel>Priority *</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select priority" />
</SelectTrigger>
</FormControl>
<SelectContent>
{priorityOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
<span className={option.color}>{option.label}</span>
</SelectItem>
))}
</SelectContent>
</Select>
<FormDescription>
Set the priority level for this epic
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="estimatedHours"
render={({ field }) => (
<FormItem>
<FormLabel>Estimated Hours</FormLabel>
<FormControl>
<Input
type="number"
placeholder="e.g., 40"
{...field}
onChange={(e) => {
const value = e.target.value;
field.onChange(value === '' ? '' : Number(value));
}}
/>
</FormControl>
<FormDescription>
Optional time estimate in hours
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</div>
<div className="flex justify-end gap-3 pt-4">
{onCancel && (
<Button
type="button"
variant="outline"
onClick={onCancel}
disabled={isLoading}
>
Cancel
</Button>
)}
<Button type="submit" disabled={isLoading || !isHydrated}>
{isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{!isHydrated ? 'Loading...' : isEditing ? 'Update Epic' : 'Create Epic'}
</Button>
</div>
</form>
</Form>
);
}