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 { InputField } from "@/components/ui/input"; import { ToggleField } from "@/components/ui/toggle"; import { useBucketContext } from "../context"; const QuotaSection = () => { const { bucket: data } = useBucketContext(); const form = useForm({ resolver: zodResolver(quotaSchema), defaultValues: { enabled: false, maxObjects: null, maxSize: null, }, }); const isEnabled = useWatch({ control: form.control, name: "enabled" }); const updateMutation = useUpdateBucket(data?.id); const handleChange = useDebounce((values: DeepPartial) => { const { enabled } = values; const maxObjects = Number(values.maxObjects); const maxSize = Math.round(Number(values.maxSize) * 1024 ** 3); const quotaData = { maxObjects: enabled && maxObjects > 0 ? maxObjects : null, maxSize: enabled && maxSize > 0 ? maxSize : null, }; updateMutation.mutate({ quotas: quotaData }); }); // Reset form when data changes without triggering watch useEffect(() => { if (!data) return; const formValues = { enabled: data.quotas?.maxSize != null || data.quotas?.maxObjects != null, maxSize: data.quotas?.maxSize ? data.quotas?.maxSize / 1024 ** 3 : null, maxObjects: data.quotas?.maxObjects || null, }; form.reset(formValues, { keepDirty: false }); }, [data, form]); // Set up form watcher useEffect(() => { const subscription = form.watch(handleChange); return () => subscription.unsubscribe(); }, [form, handleChange]); return (
{isEnabled && (
)}
); }; export default QuotaSection;