feat: Enhance session loading with cancellation and interval refresh
This commit is contained in:
22
src/App.tsx
22
src/App.tsx
@@ -12,6 +12,8 @@ const App: React.FC = () => {
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
|
||||
const load = async () => {
|
||||
setLoadState("loading");
|
||||
setErrorMessage(null);
|
||||
@@ -22,16 +24,28 @@ const App: React.FC = () => {
|
||||
(a, b) =>
|
||||
new Date(b.endedAt).getTime() - new Date(a.endedAt).getTime()
|
||||
);
|
||||
setSessions(sorted);
|
||||
setLoadState("success");
|
||||
|
||||
if (!isCancelled) {
|
||||
setSessions(sorted);
|
||||
setLoadState("success");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setErrorMessage("Could not load charging data.");
|
||||
setLoadState("error");
|
||||
if (!isCancelled) {
|
||||
setErrorMessage("Could not load charging data.");
|
||||
setLoadState("error");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
load();
|
||||
|
||||
const id = setInterval(load, 5000);
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
clearInterval(id);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const latestSession = sessions[0] ?? null;
|
||||
|
||||
Reference in New Issue
Block a user