import React, { useEffect } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; // react-hook-form import { Controller, useForm } from "react-hook-form"; // react-color import { TwitterPicker } from "react-color"; // headless ui import { Dialog, Popover, Transition } from "@headlessui/react"; // services import stateService from "services/state.service"; // ui import { Button, Input, Select, TextArea } from "components/ui"; // icons import { ChevronDownIcon } from "@heroicons/react/24/outline"; // types import type { IState } from "types"; // fetch keys import { STATE_LIST } from "constants/fetch-keys"; // constants import { GROUP_CHOICES } from "constants/project"; // types type Props = { isOpen: boolean; projectId: string; data?: IState; handleClose: () => void; }; const defaultValues: Partial = { name: "", description: "", color: "#000000", group: "backlog", }; export const CreateUpdateStateModal: React.FC = ({ isOpen, data, projectId, handleClose, }) => { const router = useRouter(); const { workspaceSlug } = router.query; const { register, formState: { errors, isSubmitting }, handleSubmit, watch, control, reset, setError, } = useForm({ defaultValues, }); useEffect(() => { if (data) { reset(data); } else { reset(defaultValues); } }, [data, reset]); const onClose = () => { handleClose(); reset(defaultValues); }; const onSubmit = async (formData: IState) => { if (!workspaceSlug) return; const payload: IState = { ...formData, }; if (!data) { await stateService .createState(workspaceSlug as string, projectId, payload) .then((res) => { mutate(STATE_LIST(projectId), (prevData) => [...(prevData ?? []), res], false); onClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof IState, { message: err[key].join(", "), }); }); }); } else { await stateService .updateState(workspaceSlug as string, projectId, data.id, payload) .then((res) => { mutate( STATE_LIST(projectId), (prevData) => { const newData = prevData?.map((item) => { if (item.id === res.id) { return res; } return item; }); return newData; }, false ); onClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof IState, { message: err[key].join(", "), }); }); }); } }; return (
{data ? "Update" : "Create"} State