import { DeepPartial, useForm, useWatch } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { QuotaSchema, quotaSchema } from "../schema"; import { useEffect } from "react"; import { useDebounce } from "@/hooks/useDebounce"; import { useUpdateBucket } from "../hooks"; import { Bucket } from "../../types"; import { InputField } from "@/components/ui/input"; import { ToggleField } from "@/components/ui/toggle"; type Props = { data?: Bucket; }; const QuotaSection = ({ data }: Props) => { const form = useForm({ resolver: zodResolver(quotaSchema), }); const isEnabled = useWatch({ control: form.control, name: "enabled" }); const updateMutation = useUpdateBucket(data?.id); const onChange = useDebounce((values: DeepPartial) => { const { enabled } = values; const maxObjects = Number(values.maxObjects); const maxSize = Math.round(Number(values.maxSize) * 1024 * 1024); const data = { maxObjects: enabled && maxObjects > 0 ? maxObjects : null, maxSize: enabled && maxSize > 0 ? maxSize : null, }; updateMutation.mutate({ quotas: data }); }); useEffect(() => { form.reset({ enabled: data?.quotas?.maxSize != null || data?.quotas?.maxObjects != null, maxSize: data?.quotas?.maxSize ? data?.quotas?.maxSize / 1024 / 1024 : null, maxObjects: data?.quotas?.maxObjects || null, }); const { unsubscribe } = form.watch((values) => onChange(values)); return unsubscribe; }, [data]); return (
{isEnabled && (
)}
); }; export default QuotaSection;