42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
|
|
import { useMutation, useQuery } from "@tanstack/react-query";
|
||
|
|
import { CAM_BASE } from "../utils/config";
|
||
|
|
import { toast } from "sonner";
|
||
|
|
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : CAM_BASE;
|
||
|
|
|
||
|
|
const uploadFile = async (file: File) => {
|
||
|
|
const form = new FormData();
|
||
|
|
form.append("upload", file, file.name);
|
||
|
|
const response = await fetch(`${camBase}/upload/file-upload/3`, {
|
||
|
|
method: "POST",
|
||
|
|
body: form,
|
||
|
|
});
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error("Cannot reach upload file endpoint");
|
||
|
|
}
|
||
|
|
return response.text();
|
||
|
|
};
|
||
|
|
|
||
|
|
const getUploadFiles = async () => {
|
||
|
|
const response = await fetch(`${camBase}/upload/file-upload/3`);
|
||
|
|
if (!response.ok) {
|
||
|
|
throw new Error("Cannot reach upload file endpoint");
|
||
|
|
}
|
||
|
|
return response.json();
|
||
|
|
};
|
||
|
|
|
||
|
|
export const useFileUpload = () => {
|
||
|
|
const query = useQuery({
|
||
|
|
queryKey: ["getUploadFiles"],
|
||
|
|
queryFn: getUploadFiles,
|
||
|
|
});
|
||
|
|
|
||
|
|
const mutation = useMutation({
|
||
|
|
mutationFn: (file: File) => uploadFile(file),
|
||
|
|
mutationKey: ["uploadFile"],
|
||
|
|
onError: (err) => console.log(err),
|
||
|
|
onSuccess: (msg) => toast.success(msg),
|
||
|
|
});
|
||
|
|
|
||
|
|
return { query, mutation };
|
||
|
|
};
|