Files
Mav-Mobile-UI/src/hooks/useCameraConfig.ts

59 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-09-12 08:21:52 +01:00
import { useMutation, useQuery } from "@tanstack/react-query";
2025-09-12 13:28:14 +01:00
import { toast } from "sonner";
import { CAM_BASE } from "../utils/config";
2025-09-12 08:21:52 +01:00
const base_url = `${CAM_BASE}/api`;
2025-09-12 08:21:52 +01:00
2025-09-12 13:28:14 +01:00
const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
2025-09-12 08:21:52 +01:00
const [, cameraSide] = queryKey;
const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
const response = await fetch(fetchUrl, {
signal: AbortSignal.timeout(300000),
});
2025-09-12 08:21:52 +01:00
if (!response.ok) throw new Error("cannot react cameraSide ");
return response.json();
};
const updateCamerasideConfig = async (data: { id: string | number; friendlyName: string; cameraAddress: string }) => {
2025-09-12 08:21:52 +01:00
const updateUrl = `${base_url}/update-config?id=${data.id}`;
const updateConfigPayload = {
id: data.friendlyName,
2025-09-12 08:21:52 +01:00
fields: [
{
property: "propURI",
value: data.cameraAddress,
2025-09-12 08:21:52 +01:00
},
],
};
2025-09-12 08:21:52 +01:00
const response = await fetch(updateUrl, {
method: "POST",
body: JSON.stringify(updateConfigPayload),
});
2025-11-10 13:44:29 +00:00
if (!response.ok) throw new Error("Please make sure fields are filled in correctly");
2025-09-12 08:21:52 +01:00
};
export const useFetchCameraConfig = (cameraSide: string) => {
const fetchedConfigQuery = useQuery({
queryKey: ["cameraSideConfig", cameraSide],
queryFn: fetchCameraSideConfig,
});
const updateConfigMutation = useMutation({
mutationKey: ["cameraSideConfigUpdate"],
mutationFn: updateCamerasideConfig,
2025-09-12 13:28:14 +01:00
onError: (error) => toast.error(error.message),
onSuccess: () => toast("Settings Successfully saved"),
2025-09-12 08:21:52 +01:00
});
return {
data: fetchedConfigQuery.data,
isPending: fetchedConfigQuery.isPending,
isError: fetchedConfigQuery.isError,
updateCameraConfig: updateConfigMutation.mutate,
2025-09-12 13:28:14 +01:00
updateCameraConfigError: updateConfigMutation.error,
updateCameraConfigLoading: updateConfigMutation.isPending,
2025-09-12 08:21:52 +01:00
};
};