import { useRouter } from "@tanstack/react-router";
import { useState } from "react";
/** Avatars go to a raw Worker route (binary body) rather than a server function. */
export function useAvatarUpload(account: string) {
const router = useRouter();
const [pending, setPending] = useState(false);
const [error, setError] = useState<string | null>(null);
async function upload(file: File) {
setPending(true);
setError(null);
try {
const response = await fetch(`/settings/avatar?account=${encodeURIComponent(account)}`, {
method: "POST",
headers: { "content-type": file.type, "x-stig-csrf": "1" },
body: file,
});
if (!response.ok) throw new Error((await response.text()) || "Upload failed");
await router.invalidate();
} catch (caught) {
setError(caught instanceof Error ? caught.message : "Upload failed");
} finally {
setPending(false);
}
}
return { upload, pending, error };
}