Displaying the game library with server side pagination

This commit is contained in:
Andreas Dahm committed 2026-05-04 11:48:08 +02:00
1 parent 994f4a516b
commit 8b290d5a13
8 files changed
+367 -5

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
import {useEffect, useRef, useState} from 'react';
const POLL_INTERVAL_MS = 3000;
const MAX_POLL_DURATION_MS = 120_000;
const INITIAL_SYNC_GRACE_MS = 15_000;
/**
* Polls /api/library/sync-status while a sync is running (or expected),
* and fires onComplete once when the run transitions to OK / FAILED.
*
* @param {Object} opts
* @param {boolean} opts.enabled - skip work entirely when false (e.g. user has no steamId)
* @param {boolean} opts.expectInitialSync - if true and no row yet, keep polling (covers the
* gap between async sync dispatch and first DB write)
* @param {() => void} opts.onComplete - called once per transition to OK/FAILED
* @returns {{status: string|null, lastSyncedAt: string|null, isRunning: boolean, error: string|null}}
*/
export default function useLibrarySync({enabled, expectInitialSync = false, onComplete}) {
const [state, setState] = useState({status: null, lastSyncedAt: null, error: null});
const previousRunningRef = useRef(null);
const onCompleteRef = useRef(onComplete);
onCompleteRef.current = onComplete;
useEffect(() => {
if (!enabled) return undefined;
let cancelled = false;
let timer = null;
const startedAt = Date.now();
const fetchOnce = async () => {
const token = localStorage.getItem('tbp_jwt');
if (!token) return;
try {
const response = await fetch(
`${import.meta.env.VITE_CORE_API_URL}/api/library/sync-status`,
{headers: {'Authorization': `Bearer ${token}`}}
);
if (cancelled) return;
if (!response.ok) {
setState((s) => ({...s, error: 'sync-status fetch failed'}));
return;
}
const json = await response.json();
if (cancelled) return;
const status = json.lastSyncStatus;
const lastSyncedAt = json.lastSyncedAt;
setState({status, lastSyncedAt, error: null});
const isRunning = status === 'RUNNING';
const wasRunning = previousRunningRef.current;
if (wasRunning === true && !isRunning) {
onCompleteRef.current?.();
}
previousRunningRef.current = isRunning;
const elapsed = Date.now() - startedAt;
const waitingForInitial =
expectInitialSync && status == null && elapsed < INITIAL_SYNC_GRACE_MS;
const stillWaiting = isRunning || waitingForInitial;
if (stillWaiting && elapsed < MAX_POLL_DURATION_MS) {
timer = setTimeout(fetchOnce, POLL_INTERVAL_MS);
}
} catch (err) {
if (cancelled) return;
console.error('sync-status poll error:', err);
setState((s) => ({...s, error: 'network'}));
}
};
fetchOnce();
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [enabled, expectInitialSync]);
return {
status: state.status,
lastSyncedAt: state.lastSyncedAt,
isRunning: state.status === 'RUNNING',
error: state.error,
};
}