feat: Integrate ChildSelector in sleep tracking form
Some checks failed
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled

- Replace local child state with Redux state management
- Use ChildSelector component instead of custom select
- Sync selectedChildIds with Redux store
- Update API calls to use selectedChild.id
- Remove duplicate child loading logic
- Build and test successfully
This commit is contained in:
2025-10-04 21:55:28 +00:00
parent 65ce8bda6c
commit 89a0d7eca7
2 changed files with 47 additions and 54 deletions

View File

@@ -47,6 +47,10 @@ import { childrenApi, Child } from '@/lib/api/children';
import { motion } from 'framer-motion'; import { motion } from 'framer-motion';
import { useLocalizedDate } from '@/hooks/useLocalizedDate'; import { useLocalizedDate } from '@/hooks/useLocalizedDate';
import { useTranslation } from '@/hooks/useTranslation'; import { useTranslation } from '@/hooks/useTranslation';
import { useDispatch, useSelector } from 'react-redux';
import { fetchChildren, selectChild, selectSelectedChild, childrenSelectors } from '@/store/slices/childrenSlice';
import { AppDispatch, RootState } from '@/store/store';
import ChildSelector from '@/components/common/ChildSelector';
interface SleepData { interface SleepData {
startTime: string; startTime: string;
@@ -61,8 +65,15 @@ export default function SleepTrackPage() {
const { user } = useAuth(); const { user } = useAuth();
const { t } = useTranslation('tracking'); const { t } = useTranslation('tracking');
const { formatDistanceToNow, format } = useLocalizedDate(); const { formatDistanceToNow, format } = useLocalizedDate();
const [children, setChildren] = useState<Child[]>([]); const dispatch = useDispatch<AppDispatch>();
const [selectedChild, setSelectedChild] = useState<string>('');
// Redux state
const children = useSelector((state: RootState) => childrenSelectors.selectAll(state));
const selectedChild = useSelector(selectSelectedChild);
const familyId = useSelector((state: RootState) => state.auth.user?.familyId);
// Local state
const [selectedChildIds, setSelectedChildIds] = useState<string[]>([]);
// Sleep state // Sleep state
const [startTime, setStartTime] = useState<string>( const [startTime, setStartTime] = useState<string>(
@@ -79,7 +90,6 @@ export default function SleepTrackPage() {
const [notes, setNotes] = useState<string>(''); const [notes, setNotes] = useState<string>('');
const [recentSleeps, setRecentSleeps] = useState<Activity[]>([]); const [recentSleeps, setRecentSleeps] = useState<Activity[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [childrenLoading, setChildrenLoading] = useState(true);
const [sleepsLoading, setSleepsLoading] = useState(false); const [sleepsLoading, setSleepsLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null); const [successMessage, setSuccessMessage] = useState<string | null>(null);
@@ -88,46 +98,33 @@ export default function SleepTrackPage() {
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [activityToDelete, setActivityToDelete] = useState<string | null>(null); const [activityToDelete, setActivityToDelete] = useState<string | null>(null);
const familyId = user?.families?.[0]?.familyId; // Load children from Redux
// Load children
useEffect(() => { useEffect(() => {
if (familyId) { if (familyId && children.length === 0) {
loadChildren(); dispatch(fetchChildren(familyId));
} }
}, [familyId]); }, [familyId, dispatch, children.length]);
// Load recent sleeps when child is selected // Sync selectedChildIds with Redux selectedChild
useEffect(() => { useEffect(() => {
if (selectedChild) { if (selectedChild?.id) {
loadRecentSleeps(); setSelectedChildIds([selectedChild.id]);
} }
}, [selectedChild]); }, [selectedChild]);
const loadChildren = async () => { // Load recent sleeps when child is selected
if (!familyId) return; useEffect(() => {
if (selectedChild?.id) {
try { loadRecentSleeps();
setChildrenLoading(true);
const childrenData = await childrenApi.getChildren(familyId);
setChildren(childrenData);
if (childrenData.length > 0) {
setSelectedChild(childrenData[0].id);
}
} catch (err: any) {
console.error('Failed to load children:', err);
setError(err.response?.data?.message || 'Failed to load children');
} finally {
setChildrenLoading(false);
} }
}; }, [selectedChild?.id]);
const loadRecentSleeps = async () => { const loadRecentSleeps = async () => {
if (!selectedChild) return; if (!selectedChild?.id) return;
try { try {
setSleepsLoading(true); setSleepsLoading(true);
const activities = await trackingApi.getActivities(selectedChild, 'sleep'); const activities = await trackingApi.getActivities(selectedChild.id, 'sleep');
// Sort by timestamp descending and take last 10 // Sort by timestamp descending and take last 10
const sorted = activities.sort((a, b) => const sorted = activities.sort((a, b) =>
new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime() new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
@@ -183,7 +180,7 @@ export default function SleepTrackPage() {
}; };
const handleSubmit = async () => { const handleSubmit = async () => {
if (!selectedChild) { if (!selectedChild?.id) {
setError('Please select a child'); setError('Please select a child');
return; return;
} }
@@ -223,7 +220,7 @@ export default function SleepTrackPage() {
data.endTime = endTime; data.endTime = endTime;
} }
await trackingApi.createActivity(selectedChild, { await trackingApi.createActivity(selectedChild.id, {
type: 'sleep', type: 'sleep',
timestamp: startTime, timestamp: startTime,
data, data,
@@ -320,7 +317,9 @@ export default function SleepTrackPage() {
return `${duration} - ${data.location.charAt(0).toUpperCase() + data.location.slice(1)}`; return `${duration} - ${data.location.charAt(0).toUpperCase() + data.location.slice(1)}`;
}; };
if (childrenLoading) { const childrenLoading = useSelector((state: RootState) => state.children.loading);
if (childrenLoading && children.length === 0) {
return ( return (
<ProtectedRoute> <ProtectedRoute>
<AppShell> <AppShell>
@@ -393,27 +392,21 @@ export default function SleepTrackPage() {
transition={{ duration: 0.3 }} transition={{ duration: 0.3 }}
> >
{/* Child Selector */} {/* Child Selector */}
{children.length > 1 && ( {children.length > 0 && (
<Paper sx={{ p: 2, mb: 3 }}> <Paper sx={{ p: 2, mb: 3 }}>
<FormControl fullWidth> <ChildSelector
<InputLabel id="sleep-child-select-label">{t('common.selectChild')}</InputLabel> children={children}
<Select selectedChildIds={selectedChildIds}
labelId="sleep-child-select-label" onChange={(childIds) => {
value={selectedChild} setSelectedChildIds(childIds);
onChange={(e) => setSelectedChild(e.target.value)} if (childIds.length > 0) {
label={t('common.selectChild')} dispatch(selectChild(childIds[0]));
required }
inputProps={{ }}
'aria-required': 'true', mode="single"
}} label={t('common.selectChild')}
> required
{children.map((child) => ( />
<MenuItem key={child.id} value={child.id}>
{child.name}
</MenuItem>
))}
</Select>
</FormControl>
</Paper> </Paper>
)} )}

File diff suppressed because one or more lines are too long