import React, { useEffect } from "react"; // swr import { mutate } from "swr"; // react hook form import { useForm } from "react-hook-form"; // headless import { Dialog, Transition } from "@headlessui/react"; // ui import { Button, Input, TextArea, Select } from "ui"; // services import modulesService from "lib/services/modules.service"; // hooks import useUser from "lib/hooks/useUser"; // types import type { IModule } from "types"; // common import { renderDateFormat } from "constants/common"; // fetch keys import { MODULE_LIST } from "constants/fetch-keys"; type Props = { isOpen: boolean; setIsOpen: React.Dispatch>; projectId: string; data?: IModule; }; const defaultValues: Partial = { name: "", description: "", }; const CreateUpdateModuleModal: React.FC = ({ isOpen, setIsOpen, data, projectId }) => { const handleClose = () => { setIsOpen(false); const timeout = setTimeout(() => { reset(defaultValues); clearTimeout(timeout); }, 500); }; const { activeWorkspace } = useUser(); const { register, formState: { errors, isSubmitting }, handleSubmit, reset, setError, } = useForm({ defaultValues, }); const onSubmit = async (formData: IModule) => { if (!activeWorkspace) return; const payload = { ...formData, start_date: formData.start_date ? renderDateFormat(formData.start_date) : null, target_date: formData.target_date ? renderDateFormat(formData.target_date) : null, }; if (!data) { await modulesService .createModule(activeWorkspace.slug, projectId, payload) .then((res) => { mutate( MODULE_LIST(projectId), (prevData) => [res, ...(prevData ?? [])], false ); handleClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } else { await modulesService .updateModule(activeWorkspace.slug, projectId, data.id, payload) .then((res) => { mutate( MODULE_LIST(projectId), (prevData) => { const newData = prevData?.map((item) => { if (item.id === res.id) { return res; } return item; }); return newData; }, false ); handleClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof typeof defaultValues, { message: err[key].join(", "), }); }); }); } }; useEffect(() => { if (data) { setIsOpen(true); reset(data); } else { reset(defaultValues); } }, [data, setIsOpen, reset]); return (
{data ? "Update" : "Create"} Module