diff --git a/src/features/flight-session/model/useFlightSession.ts b/src/features/flight-session/model/useFlightSession.ts index efa161b..e98a77c 100644 --- a/src/features/flight-session/model/useFlightSession.ts +++ b/src/features/flight-session/model/useFlightSession.ts @@ -41,23 +41,33 @@ const formatHHMMSS = (totalSeconds: number) => { export function useFlightSession() { const router = useRouter(); - const [voyage] = useState(() => getVoyageFromStore()); - const [timeLeft, setTimeLeft] = useState(() => - getInitialTimerSeconds(getVoyageFromStore()), - ); + const [voyage, setVoyage] = useState(null); + const [timeLeft, setTimeLeft] = useState(0); const [isPaused, setIsPaused] = useState(false); - const endTimeRef = useRef(getEndTime(getVoyageFromStore())); + const [isSessionReady, setIsSessionReady] = useState(false); + const endTimeRef = useRef(0); const pausedElapsedMsRef = useRef(0); const pausedAtMsRef = useRef(null); useEffect(() => { + const storedVoyage = getVoyageFromStore(); + if (storedVoyage) { + setVoyage(storedVoyage); + setTimeLeft(getInitialTimerSeconds(storedVoyage)); + endTimeRef.current = getEndTime(storedVoyage); + } + setIsSessionReady(true); + }, []); + + useEffect(() => { + if (!isSessionReady) return; if (voyage) return; router.replace('/'); - }, [voyage, router]); + }, [isSessionReady, voyage, router]); useEffect(() => { - if (!voyage || isPaused) return; + if (!isSessionReady || !voyage || isPaused) return; const interval = setInterval(() => { if (voyage.durationMinutes === 0) { @@ -78,7 +88,7 @@ export function useFlightSession() { }, 1000); return () => clearInterval(interval); - }, [voyage, isPaused]); + }, [isSessionReady, voyage, isPaused]); const handlePauseToggle = () => { if (voyage?.durationMinutes === 0) {