import React from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; import { useForm } from "react-hook-form"; import { Dialog, Transition } from "@headlessui/react"; // hooks // types import type { IModule, ModuleLink } from "types"; // services import modulesService from "services/modules.service"; // ui import { Button, Input } from "components/ui"; // fetch-keys import { MODULE_LIST } from "constants/fetch-keys"; type Props = { isOpen: boolean; module: IModule | undefined; handleClose: () => void; }; const defaultValues: ModuleLink = { title: "", url: "", }; const ModuleLinkModal: React.FC = ({ isOpen, module, handleClose }) => { const router = useRouter(); const { workspaceSlug, projectId, moduleId } = router.query; const { register, formState: { errors, isSubmitting }, handleSubmit, reset, setError, } = useForm({ defaultValues, }); const onSubmit = async (formData: ModuleLink) => { if (!workspaceSlug || !projectId || !module) return; const previousLinks = module.link_module.map((l) => ({ title: l.title, url: l.url })); const payload: Partial = { links_list: [...previousLinks, formData], }; await modulesService .patchModule(workspaceSlug as string, projectId as string, module.id, payload) .then(() => { mutate(projectId && MODULE_LIST(projectId as string), (prevData) => (prevData ?? []).map((module) => { if (module.id === moduleId) return { ...module, ...payload }; return module; }) ); onClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof ModuleLink, { message: err[key].join(", "), }); }); }); }; const onClose = () => { handleClose(); const timeout = setTimeout(() => { reset(defaultValues); clearTimeout(timeout); }, 500); }; return (
Add Link
); }; export default ModuleLinkModal;