Files
Checkmate/client/src/Pages/StatusPage/Status/Hooks/useStatusPageFetch.jsx
T

53 lines
1.6 KiB
React
Raw Normal View History

2025-02-04 13:06:42 -08:00
import { useEffect, useState, useCallback } from "react";
2025-02-03 15:12:00 -08:00
import { networkService } from "../../../../main";
import { useSelector } from "react-redux";
import { createToast } from "../../../../Utils/toastUtils";
2025-02-04 13:06:42 -08:00
import { useTheme } from "@emotion/react";
2025-02-06 14:57:18 -08:00
import { useMonitorUtils } from "../../../../Hooks/useMonitorUtils";
2025-02-02 21:26:48 -08:00
2025-02-10 13:46:26 -08:00
const useStatusPageFetch = (isCreate = false, url) => {
2025-02-02 21:26:48 -08:00
const [isLoading, setIsLoading] = useState(true);
const [networkError, setNetworkError] = useState(false);
const [statusPage, setStatusPage] = useState(undefined);
2025-02-04 13:06:42 -08:00
const [monitors, setMonitors] = useState(undefined);
const theme = useTheme();
2025-02-06 14:57:18 -08:00
const { getMonitorWithPercentage } = useMonitorUtils();
2025-02-04 13:06:42 -08:00
const fetchStatusPage = useCallback(async () => {
try {
2025-02-10 13:46:26 -08:00
const response = await networkService.getStatusPageByUrl({
url,
type: "uptime",
});
2025-02-04 13:06:42 -08:00
if (!response?.data?.data) return;
const { statusPage, monitors } = response.data.data;
setStatusPage(statusPage);
const monitorsWithPercentage = monitors.map((monitor) =>
getMonitorWithPercentage(monitor, theme)
);
2025-02-07 14:50:14 -08:00
2025-02-04 13:06:42 -08:00
setMonitors(monitorsWithPercentage);
} catch (error) {
// If there is a 404, status page is not found
if (error?.response?.status === 404) {
setStatusPage(undefined);
return;
2025-02-03 15:12:00 -08:00
}
2025-02-04 13:06:42 -08:00
createToast({ body: error.message });
setNetworkError(true);
} finally {
setIsLoading(false);
}
}, [theme, getMonitorWithPercentage, url]);
2025-02-05 10:57:28 -08:00
2025-02-04 13:06:42 -08:00
useEffect(() => {
2025-02-05 10:57:28 -08:00
if (isCreate === true) {
return;
}
2025-02-03 15:12:00 -08:00
fetchStatusPage();
2025-02-05 10:57:28 -08:00
}, [isCreate, fetchStatusPage]);
2025-02-02 21:26:48 -08:00
2025-02-04 13:06:42 -08:00
return [statusPage, monitors, isLoading, networkError, fetchStatusPage];
2025-02-02 21:26:48 -08:00
};
export { useStatusPageFetch };