70 lines
1.7 KiB
TypeScript
70 lines
1.7 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, useCallback } from "react";
|
|
|
|
export function useHA(refreshInterval = 10000) {
|
|
const [data, setData] = useState<any>(null);
|
|
const [loading, setLoading] = useState(true);
|
|
|
|
const refresh = useCallback(async () => {
|
|
try {
|
|
const res = await fetch("/api/ha", { cache: "no-store" });
|
|
const json = await res.json();
|
|
setData(json);
|
|
} catch (e) {
|
|
console.error("HA fetch failed", e);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
refresh();
|
|
const id = setInterval(refresh, refreshInterval);
|
|
return () => clearInterval(id);
|
|
}, [refresh, refreshInterval]);
|
|
|
|
return { data, loading, refresh };
|
|
}
|
|
|
|
export function useWeather() {
|
|
const [weather, setWeather] = useState<any>(null);
|
|
|
|
const fetchWeather = useCallback(async () => {
|
|
try {
|
|
const res = await fetch("/api/weather", { cache: "no-store" });
|
|
const json = await res.json();
|
|
setWeather(json);
|
|
} catch (e) {
|
|
setWeather({ temp: "—", desc: "Нет данных", weatherCode: "116", forecast: [] });
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
fetchWeather();
|
|
// Refresh every 10 minutes
|
|
const id = setInterval(fetchWeather, 10 * 60 * 1000);
|
|
return () => clearInterval(id);
|
|
}, [fetchWeather]);
|
|
|
|
return weather;
|
|
}
|
|
|
|
export function useTasks() {
|
|
const [tasks, setTasks] = useState<any[]>([]);
|
|
|
|
const refresh = useCallback(async () => {
|
|
try {
|
|
const res = await fetch("/api/tasks", { cache: "no-store" });
|
|
const json = await res.json();
|
|
setTasks(json.tasks || []);
|
|
} catch (e) {}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
refresh();
|
|
}, [refresh]);
|
|
|
|
return { tasks, setTasks, refresh };
|
|
}
|