mirror of
https://github.com/xiaozhou233/RiverWaterQualityMonitoring.git
synced 2026-12-05 21:15:55 +08:00
控制面板更新 HTML+JS切换为Vite+ React + Tailwind CSS
This commit is contained in:
1 parent
4b06470590
commit
fe0b92e4b4
28 files changed
+5235
-960
No files matched your search
@@ -0,0 +1,47 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { getWaterData } from "../api/water";
|
||||
import type { WaterData } from "../types/water";
|
||||
|
||||
export function useWaterData(pollingInterval = 3000) {
|
||||
const [data, setData] = useState<WaterData | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
setError("");
|
||||
setIsLoading(true);
|
||||
const result = await getWaterData();
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Unknown error";
|
||||
setError(`加载数据失败: ${message}`);
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setInterval(() => {
|
||||
void load();
|
||||
}, pollingInterval);
|
||||
|
||||
const timeoutId = window.setTimeout(() => {
|
||||
void load();
|
||||
}, 0);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
window.clearTimeout(timeoutId);
|
||||
};
|
||||
}, [load, pollingInterval]);
|
||||
|
||||
return {
|
||||
data,
|
||||
error,
|
||||
isLoading,
|
||||
refetch: load,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user