57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
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`, {
|
|
signal: AbortSignal.timeout(500),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error("Failed to fetch blackboard data");
|
|
}
|
|
return response.json();
|
|
};
|
|
|
|
const viewBlackboardData = async (options: CameraBlackBoardOptions) => {
|
|
const response = await fetch(`${CAM_BASE}/api/blackboard`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(options),
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error("Failed to fetch blackboard data");
|
|
}
|
|
return response.json();
|
|
};
|
|
|
|
export const useCameraBlackboard = () => {
|
|
const query = useQuery({
|
|
queryKey: ["cameraBlackboard"],
|
|
queryFn: getAllBlackboardData,
|
|
});
|
|
|
|
const mutation = useMutation({
|
|
mutationKey: ["cameraBlackboard"],
|
|
mutationFn: (options?: CameraBlackBoardOptions) =>
|
|
viewBlackboardData({
|
|
operation: options?.operation,
|
|
path: options?.path,
|
|
value: options?.value,
|
|
}),
|
|
onError: (error) => {
|
|
toast.error(`cannot get data: ${error.message}`, {
|
|
id: "viewBlackboardData",
|
|
});
|
|
},
|
|
});
|
|
|
|
useEffect(() => {
|
|
if (query.isError)
|
|
toast.error(query.error.message, { id: "viewBlackboardData" });
|
|
}, [query?.error?.message, query.isError]);
|
|
|
|
return { query, mutation };
|
|
};
|