Updated loading states and error states accross app

This commit is contained in:
2025-10-06 14:21:56 +01:00
parent ad0ffa6df6
commit f275f50383
25 changed files with 377 additions and 101 deletions

View File

@@ -1,9 +1,13 @@
import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { CameraBlackBoardOptions } from "../types/types";
import { useEffect } from "react";
import { toast } from "sonner";
const getAllBlackboardData = async () => {
const response = await fetch(`${CAM_BASE}/api/blackboard`);
const response = await fetch(`${CAM_BASE}/api/blackboard`, {
signal: AbortSignal.timeout(500),
});
if (!response.ok) {
throw new Error("Failed to fetch blackboard data");
}
@@ -36,7 +40,14 @@ export const useCameraBlackboard = () => {
path: options?.path,
value: options?.value,
}),
onError: (error) => {
toast.error(`cannot get data: ${error.message}`);
},
});
useEffect(() => {
if (query.isError) toast.error(query.error.message);
}, [query?.error?.message, query.isError]);
return { query, mutation };
};

View File

@@ -4,10 +4,14 @@ import { CAM_BASE } from "../utils/config";
const base_url = `${CAM_BASE}/api`;
const fetch_url = `http://100.82.205.44/api/fetch-config?id=Colour`;
console.log(fetch_url);
const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
const [, cameraSide] = queryKey;
const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
const response = await fetch(fetchUrl);
const response = await fetch(fetchUrl, {
signal: AbortSignal.timeout(500),
});
if (!response.ok) throw new Error("cannot react cameraSide ");
return response.json();
};
@@ -53,5 +57,6 @@ export const useFetchCameraConfig = (cameraSide: string) => {
isError: fetchedConfigQuery.isError,
updateCameraConfig: updateConfigMutation.mutate,
updateCameraConfigError: updateConfigMutation.error,
updateCameraConfigLoading: updateConfigMutation.isPending,
};
};

View File

@@ -1,10 +1,15 @@
import { useQuery, useMutation } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { ModemConfig, WifiConfig } from "../types/types";
import { useEffect } from "react";
import { toast } from "sonner";
const getWiFiSettings = async () => {
const response = await fetch(
`${CAM_BASE}/api/fetch-config?id=ModemAndWifiManager-wifi`
`${CAM_BASE}/api/fetch-config?id=ModemAndWifiManager-wifi`,
{
signal: AbortSignal.timeout(500),
}
);
if (!response.ok) {
throw new Error("Cannot fetch Wifi settings");
@@ -29,7 +34,10 @@ const updateWifiSettings = async (wifiConfig: WifiConfig) => {
const getModemSettings = async () => {
const response = await fetch(
`${CAM_BASE}/api/fetch-config?id=ModemAndWifiManager-modem`
`${CAM_BASE}/api/fetch-config?id=ModemAndWifiManager-modem`,
{
signal: AbortSignal.timeout(500),
}
);
if (!response.ok) {
throw new Error("Cannot fetch modem settings");
@@ -61,7 +69,13 @@ export const useWifiAndModem = () => {
const wifiMutation = useMutation({
mutationKey: ["updateWifiSettings"],
mutationFn: (wifiConfig: WifiConfig) => updateWifiSettings(wifiConfig),
onError: (error) => console.log(error),
onError: (error) => {
toast.error("Failed to update WiFi settings");
console.error(error);
},
onSuccess: () => {
toast.success("WiFi settings updated successfully");
},
});
const modemQuery = useQuery({
@@ -72,8 +86,22 @@ export const useWifiAndModem = () => {
const modemMutation = useMutation({
mutationKey: ["updateModemSettings"],
mutationFn: (modemConfig: ModemConfig) => updateModemSettings(modemConfig),
onError: (error) => {
toast.error("Failed to update Modem settings");
console.error(error);
},
onSuccess: () => {
toast.success("Modem settings updated successfully");
},
});
useEffect(() => {
if (wifiQuery.isError) toast.error("Cannot get WiFi settings");
}, [wifiQuery?.error?.message, wifiQuery.isError]);
useEffect(() => {
if (modemQuery.isError) toast.error("Cannot get Modem settings");
}, [modemQuery?.error?.message, modemQuery.isError]);
return {
wifiQuery,
wifiMutation,

View File

@@ -8,7 +8,10 @@ import type { zoomConfig, ZoomInOptions } from "../types/types";
async function zoomIn(options: ZoomInOptions) {
const response = await fetch(
`${CAM_BASE}/Ip${options.camera}-command?magnification=${options.multiplier}x`
`${CAM_BASE}/Ip${options.camera}-command?magnification=${options.multiplier}x`,
{
signal: AbortSignal.timeout(500),
}
);
if (!response.ok) {
throw new Error("Cannot reach camera zoom endpoint");
@@ -21,7 +24,9 @@ async function fetchZoomInConfig({
queryKey,
}: QueryFunctionContext<[string, zoomConfig]>) {
const [, { camera }] = queryKey;
const response = await fetch(`${CAM_BASE}/Ip${camera}-inspect`);
const response = await fetch(`${CAM_BASE}/Ip${camera}-inspect`, {
signal: AbortSignal.timeout(500),
});
if (!response.ok) {
throw new Error("Cannot get camera zoom settings");
}

View File

@@ -3,9 +3,11 @@ import { useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
const apiUrl = CAM_BASE;
// const fetch_url = `http://100.82.205.44/Colour-preview`;
async function fetchSnapshot(cameraSide: string) {
const response = await fetch(`${apiUrl}/${cameraSide}-preview`);
const response = await fetch(`${apiUrl}/${cameraSide}-preview`, {
signal: AbortSignal.timeout(500),
});
if (!response.ok) {
throw new Error("Cannot reach endpoint");
}
@@ -75,9 +77,5 @@ export function useGetOverviewSnapshot(side: string) {
};
}, [drawImage]);
if (isError) {
console.error("Snapshot error:", error);
}
return { canvasRef, isError, isPending };
return { canvasRef, isError, error, isPending };
}

View File

@@ -3,10 +3,13 @@ import type { NPEDFieldType } from "../types/types";
import { useNPEDContext } from "../context/NPEDUserContext";
import { useEffect } from "react";
import { CAM_BASE } from "../utils/config";
import { toast } from "sonner";
async function fetchNPEDDetails() {
const fetchUrl = `${CAM_BASE}/api/fetch-config?id=NPED`;
const response = await fetch(fetchUrl);
const response = await fetch(fetchUrl, {
signal: AbortSignal.timeout(500),
});
if (!response.ok) throw new Error("Cannot reach fetch-config endpoint");
return response.json();
@@ -14,43 +17,37 @@ async function fetchNPEDDetails() {
async function signIn(loginDetails: NPEDFieldType) {
const { frontId, rearId, username, password, clientId } = loginDetails;
const NPEDLoginURLFront = `${CAM_BASE}/api/update-config?id=${frontId}`;
const NPEDLoginURLRear = `${CAM_BASE}/api/update-config?id=${rearId}`;
const frontCameraPayload = {
id: frontId,
const payload = (id: string) => ({
id,
fields: [
{ property: "propEnabled", value: true },
{ property: "propUsername", value: username },
{ property: "propPassword", value: password },
{ property: "propClientID", value: clientId },
],
};
const rearCameraPayload = {
id: rearId,
fields: [
{ property: "propEnabled", value: true },
{ property: "propUsername", value: username },
{ property: "propPassword", value: password },
{ property: "propClientID", value: clientId },
],
};
const frontCameraResponse = await fetch(NPEDLoginURLFront, {
method: "POST",
body: JSON.stringify(frontCameraPayload),
});
const rearCameraResponse = await fetch(NPEDLoginURLRear, {
method: "POST",
body: JSON.stringify(rearCameraPayload),
});
const [frontRes, rearRes] = await Promise.all([
fetch(NPEDLoginURLFront, {
method: "POST",
body: JSON.stringify(payload(frontId)),
}),
fetch(NPEDLoginURLRear, {
method: "POST",
body: JSON.stringify(payload(rearId)),
}),
]);
if (!frontCameraResponse.ok) throw new Error("cannot reach NPED endpoint");
if (!rearCameraResponse.ok) throw new Error("cannot reach NPED endpoint");
if (!frontRes.ok || !rearRes.ok)
throw new Error("Cannot reach NPED endpoint");
return {
frontResponse: frontCameraResponse.json(),
rearResponse: rearCameraResponse.json(),
frontResponse: frontRes.json(),
rearResponse: rearRes.json(),
};
}
@@ -81,12 +78,34 @@ export const useNPEDAuth = () => {
const signInMutation = useMutation({
mutationKey: ["NPEDSignin"],
mutationFn: signIn,
onSuccess: async (data) => setUser(await data.frontResponse),
onMutate: () => {
toast.loading("Signing in...");
},
onSuccess: async (data) => {
toast.dismiss();
toast.success("Signed in successfully!");
setUser(await data.frontResponse);
},
onError: (error) => {
toast.dismiss();
if (error.message.includes("timed out")) {
toast.error("Connection timed out. Please check your network.");
} else {
toast.error(`Sign-in failed: ${error.message}`);
}
},
});
const signOutMutation = useMutation({
mutationKey: ["auth", "NPEDSignOut"],
mutationFn: signOut,
onSuccess: () => {
toast.success("Signed out successfully");
setUser(null);
},
onError: (error) => {
toast.error(`Sign-out failed: ${error.message}`);
},
});
const fetchdataQuery = useQuery({
@@ -102,6 +121,10 @@ export const useNPEDAuth = () => {
}
}, [fetchdataQuery.data, fetchdataQuery.isSuccess, setUser]);
useEffect(() => {
if (fetchdataQuery.isError) toast.error(fetchdataQuery.error.message);
}, [fetchdataQuery?.error?.message, fetchdataQuery.isError]);
return {
signIn: signInMutation.mutate,
signInAsync: signInMutation.mutateAsync,
@@ -109,6 +132,8 @@ export const useNPEDAuth = () => {
isError: signInMutation.isError,
error: signInMutation.error,
data: signInMutation.data,
fetchdataQueryError: fetchdataQuery.error,
fetchdataQueryLoading: fetchdataQuery.isLoading,
user,
setUser,
signOut: signOutMutation.mutate,

View File

@@ -10,7 +10,9 @@ async function fetchSighting(
url: string | undefined,
ref: number
): Promise<SightingType> {
const res = await fetch(`${url}${ref}`);
const res = await fetch(`${url}${ref}`, {
signal: AbortSignal.timeout(5000),
});
if (!res.ok) throw new Error(String(res.status));
return res.json();
}

View File

@@ -17,7 +17,7 @@ export const useSystemConfig = () => {
const saveSystemSettings = useMutation({
mutationKey: ["systemSaveSettings"],
mutationFn: handleSystemSave,
onSuccess: () => toast("System Settings Saved Successfully!"),
onError: (error) => console.error(error.message),
});
const getSystemSettings = useQuery({
@@ -28,5 +28,8 @@ export const useSystemConfig = () => {
uploadSettings: uploadSettingsMutation.mutate,
saveSystemSettings: saveSystemSettings.mutate,
systemSettingsData: getSystemSettings.data,
systemSettingsError: getSystemSettings.error,
saveSystemSettingsError: saveSystemSettings.isError,
saveSystemSettingsLoading: saveSystemSettings.isPending,
};
};