import React, { useEffect } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; // react hook form import { Controller, useForm } from "react-hook-form"; // headless ui import { Dialog, Transition } from "@headlessui/react"; // services import cycleService from "services/cycles.service"; // hooks import useToast from "hooks/use-toast"; // ui import { Button, Input, TextArea, CustomSelect, CustomDatePicker } from "components/ui"; // common import { renderDateFormat } from "helpers/date-time.helper"; // types import type { ICycle } from "types"; // fetch keys import { CYCLE_LIST } from "constants/fetch-keys"; type Props = { isOpen: boolean; setIsOpen: React.Dispatch>; projectId: string; data?: ICycle; }; const defaultValues: Partial = { name: "", description: "", status: "draft", start_date: null, end_date: null, }; const CreateUpdateCycleModal: React.FC = ({ isOpen, setIsOpen, data, projectId }) => { const router = useRouter(); const { workspaceSlug } = router.query; const { setToastAlert } = useToast(); const { register, formState: { errors, isSubmitting }, handleSubmit, control, reset, setError, } = useForm({ defaultValues, }); useEffect(() => { if (data) { setIsOpen(true); reset(data); } else { reset(defaultValues); } }, [data, setIsOpen, reset]); const onSubmit = async (formData: ICycle) => { if (!workspaceSlug) return; const payload = { ...formData, start_date: formData.start_date ? renderDateFormat(formData.start_date) : null, end_date: formData.end_date ? renderDateFormat(formData.end_date) : null, }; if (!data) { await cycleService .createCycle(workspaceSlug as string, projectId, payload) .then((res) => { mutate(CYCLE_LIST(projectId), (prevData) => [res, ...(prevData ?? [])], false); handleClose(); setToastAlert({ title: "Success", type: "success", message: "Cycle created successfully", }); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } else { await cycleService .updateCycle(workspaceSlug as string, projectId, data.id, payload) .then((res) => { mutate(CYCLE_LIST(projectId)); handleClose(); setToastAlert({ title: "Success", type: "success", message: "Cycle updated successfully", }); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } }; const handleClose = () => { setIsOpen(false); reset(defaultValues); }; return (
{data ? "Update" : "Create"} Cycle