diff --git a/apps/frontend/src/context/DataContext.tsx b/apps/frontend/src/context/DataContext.tsx index 2f8d355d..d11eaee3 100644 --- a/apps/frontend/src/context/DataContext.tsx +++ b/apps/frontend/src/context/DataContext.tsx @@ -62,9 +62,9 @@ export const DataContextProvider = ({ clockWorker, children }: Props) => { const hasValidData = trackedData.length > 0; - const accumulatedTimeRef = useLiveRef(0); - const pausedTimeRef = useLiveRef(0); - const lastElapsedRef = useLiveRef(0); + const accumulatedTimeRef = React.useRef(0); + const pausedTimeRef = React.useRef(0); + const lastElapsedRef = React.useRef(0); const powerRef = useLiveRef(power); const heartRateRef = useLiveRef(heartRate); const cadenceRef = useLiveRef(cadence); @@ -72,9 +72,10 @@ export const DataContextProvider = ({ clockWorker, children }: Props) => { const dataTick = React.useCallback( async (delta: number) => { try { - if (accumulatedTimeRef.current > 0) { - await db.addElapsedTime(accumulatedTimeRef.current); - accumulatedTimeRef.current = 0; + const timeToFlush = accumulatedTimeRef.current; + accumulatedTimeRef.current = 0; + if (timeToFlush > 0) { + await db.addElapsedTime(timeToFlush); } const currentHeartRate = heartRateRef.current; @@ -166,6 +167,12 @@ export const DataContextProvider = ({ clockWorker, children }: Props) => { syncResistance(); } + // Initialize refs from current elapsed time when resuming a previous session + if (state === 'not_started' && workoutState.elapsedTime > 0) { + pausedTimeRef.current = workoutState.elapsedTime; + lastElapsedRef.current = workoutState.elapsedTime; + } + startActiveWorkout(); clockWorker.postMessage('startClockTimer'); setState('running'); @@ -175,6 +182,8 @@ export const DataContextProvider = ({ clockWorker, children }: Props) => { syncResistance, startActiveWorkout, trackedData.length, + state, + workoutState.elapsedTime, ]); const stop = React.useCallback(async () => { @@ -186,10 +195,11 @@ export const DataContextProvider = ({ clockWorker, children }: Props) => { clockWorker.postMessage('stopClockTimer'); - if (accumulatedTimeRef.current > 0) { + const timeToFlush = accumulatedTimeRef.current; + accumulatedTimeRef.current = 0; + if (timeToFlush > 0) { try { - await db.addElapsedTime(accumulatedTimeRef.current); - accumulatedTimeRef.current = 0; + await db.addElapsedTime(timeToFlush); } catch (error) { console.error('Failed to flush elapsed time on stop:', error); } @@ -206,14 +216,6 @@ export const DataContextProvider = ({ clockWorker, children }: Props) => { workoutState.elapsedTime, ]); - // Initialize paused time when workout state loads with existing elapsed time - React.useEffect(() => { - if (state === 'not_started' && workoutState.elapsedTime > 0) { - pausedTimeRef.current = workoutState.elapsedTime; - lastElapsedRef.current = workoutState.elapsedTime; - } - }, [workoutState.elapsedTime, state]); - return (