import React, { useEffect } from "react"; // swr import { mutate } from "swr"; // react hook form import { Controller, useForm } from "react-hook-form"; // react color import { TwitterPicker } from "react-color"; // headless import { Dialog, Popover, Transition } from "@headlessui/react"; // services import stateService from "lib/services/state.services"; // fetch keys import { STATE_LIST } from "constants/fetch-keys"; // hooks import useUser from "lib/hooks/useUser"; // ui import { Button, Input, TextArea } from "ui"; // icons import { ChevronDownIcon } from "@heroicons/react/24/outline"; // types import type { IState } from "types"; type Props = { isOpen: boolean; setIsOpen: React.Dispatch>; projectId: string; data?: IState; }; const defaultValues: Partial = { name: "", description: "", color: "#000000", }; const CreateUpdateStateModal: 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, watch, control, reset, setError, } = useForm({ defaultValues, }); const onSubmit = async (formData: IState) => { if (!activeWorkspace) return; const payload: IState = { ...formData, }; if (!data) { await stateService .createState(activeWorkspace.slug, projectId, payload) .then((res) => { mutate( STATE_LIST(projectId), (prevData) => [...(prevData ?? []), res], false ); handleClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof IState, { message: err[key].join(", "), }); }); }); } else { await stateService .updateState(activeWorkspace.slug, 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 ); handleClose(); }) .catch((err) => { Object.keys(err).map((key) => { setError(key as keyof IState, { message: err[key].join(", "), }); }); }); } }; useEffect(() => { if (data) { setIsOpen(true); reset(data); } else { reset(defaultValues); } }, [data, setIsOpen, reset]); return (
{data ? "Update" : "Create"} State
{({ open }) => ( <> Color {watch("color") && watch("color") !== "" && ( )} ( onChange(value.hex) } /> )} /> )}