Files
TREK/client/src/components/Journey/useJourneyLiveData.ts
T
Maurice 21391e483d fix(ci): resolve Journey strict checks and test contexts
Give the upload DTO an object for file-only requests, make UI error keys discoverable, and run the digest fixtures with the same ORM context as scheduled jobs.
2026-11-30 17:41:53 +01:00

56 lines
1.9 KiB
TypeScript

import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { useServerPing } from '../../sync/useServerPing';
type LoadStatus = 'idle' | 'loading' | 'ready' | 'failed';
/** Read journey data on open and server updates. Keep the last good read when a refresh fails. */
export function useJourneyLiveData<T>(journeyId: number | null, eventName: string, read: (id: number) => Promise<T>) {
const [loaded, setLoaded] = useState<{ journeyId: number; data: T } | null>(null);
const [failedFor, setFailedFor] = useState<number | null>(null);
const activeId = useRef(journeyId);
const latestRead = useRef<symbol | null>(null);
useLayoutEffect(() => {
activeId.current = journeyId;
return () => {
activeId.current = null;
latestRead.current = null;
};
}, [journeyId]);
const refresh = useCallback(async () => {
if (journeyId === null) return;
const version = Symbol();
latestRead.current = version;
await read(journeyId).then(
(data) => {
if (latestRead.current === version) setLoaded({ journeyId, data });
},
() => {
if (latestRead.current === version) setFailedFor(journeyId);
}
);
}, [journeyId, read]);
useEffect(() => {
void refresh();
}, [refresh]);
useServerPing(eventName, journeyId !== null, refresh);
const update = useCallback(
(change: (data: T | null) => T | null) => {
if (journeyId === null || activeId.current !== journeyId) return;
setLoaded((previous) => {
const data = change(previous?.journeyId === journeyId ? previous.data : null);
return data === null ? previous : { journeyId, data };
});
},
[journeyId]
);
const current = loaded?.journeyId === journeyId ? loaded : null;
const status: LoadStatus =
journeyId === null ? 'idle' : current ? 'ready' : failedFor === journeyId ? 'failed' : 'loading';
return { data: current?.data ?? null, status, update };
}