Refactor MachinesContainer: convert to TypeScript, implement SWR for data fetching, and update API routes

master^2
Tudor Stanciu 2024-11-11 02:04:02 +02:00
parent 338aa17fe8
commit 8148da132d
2 changed files with 17 additions and 17 deletions

View File

@ -1,32 +1,30 @@
import React, { useContext, useEffect, useCallback, useState } from "react";
import React, { useContext, useState } from "react";
import { NetworkStateContext, NetworkDispatchContext } from "../../network/state/contexts";
import MachinesListComponent from "./MachinesListComponent";
import PageTitle from "../../../components/common/PageTitle";
import { useTranslation } from "react-i18next";
import ViewModeSelection, { ViewModes } from "./ViewModeSelection";
import { routes, get } from "../../../utils/api";
import { endpoints } from "../../../utils/api";
import { useSWR, fetcher } from "units/swr";
import { blip } from "utils";
import { Machine } from "types";
const MachinesContainer = () => {
const MachinesContainer: React.FC = () => {
const [viewMode, setViewMode] = useState(null);
const state = useContext(NetworkStateContext);
const dispatchActions = useContext(NetworkDispatchContext);
const { t } = useTranslation();
const handleReadMachines = useCallback(async () => {
await get(routes.machines, {
onCompleted: machines => {
const data = Object.assign(machines, { loaded: true });
dispatchActions.onNetworkChange("machines", data);
}
});
}, [dispatchActions]);
useEffect(() => {
if (!state.network.machines.loaded) {
handleReadMachines();
const url = state.network.machines.loaded ? null : endpoints.network.machines;
useSWR<Machine[], Error>(url, fetcher, {
revalidateOnFocus: false,
onError: err => blip.error(err.message),
onSuccess: machines => {
const data = Object.assign(machines, { loaded: true });
dispatchActions.onNetworkChange("machines", data);
}
}, [handleReadMachines, state.network.machines.loaded]);
});
return (
<>

View File

@ -10,11 +10,13 @@ const powerActionsRoute = `${apiHost}/resurrector`;
const securityRoute = `${apiHost}/security`;
const routes = {
machines: `${networkRoute}/machines`,
wakeMachine: `${powerActionsRoute}/wake`,
pingMachine: `${powerActionsRoute}/ping`,
shutdownMachine: `${powerActionsRoute}/shutdown`,
restartMachine: `${powerActionsRoute}/restart`,
network: {
machines: `${networkRoute}/machines`
},
system: {
version: `${systemRoute}/version`,
releaseNotes: `${systemRoute}/release-notes`,