import { Dispatch, SetStateAction, useEffect, useState } from "react"; import { mutate } from "swr"; // react-hook-form import { Controller, useForm } from "react-hook-form"; // services import workspaceService from "services/workspace.service"; // hooks import useToast from "hooks/use-toast"; // ui import { CustomSelect, Input, PrimaryButton } from "components/ui"; // types import { IWorkspace } from "types"; // fetch-keys import { USER_WORKSPACES } from "constants/fetch-keys"; // constants import { COMPANY_SIZE } from "constants/workspace"; type Props = { onSubmit: (res: IWorkspace) => void; defaultValues: { name: string; slug: string; company_size: number | null; }; setDefaultValues: Dispatch>; }; export const CreateWorkspaceForm: React.FC = ({ onSubmit, defaultValues, setDefaultValues, }) => { const [slugError, setSlugError] = useState(false); const { setToastAlert } = useToast(); const { register, handleSubmit, control, setValue, getValues, formState: { errors, isSubmitting }, } = useForm({ defaultValues }); const handleCreateWorkspace = async (formData: IWorkspace) => { await workspaceService .workspaceSlugCheck(formData.slug) .then(async (res) => { if (res.status === true) { setSlugError(false); await workspaceService .createWorkspace(formData) .then((res) => { setToastAlert({ type: "success", title: "Success!", message: "Workspace created successfully.", }); mutate(USER_WORKSPACES, (prevData) => [res, ...(prevData ?? [])]); onSubmit(res); }) .catch((err) => { console.error(err); }); } else setSlugError(true); }) .catch(() => { setToastAlert({ type: "error", title: "Error!", message: "Some error occurred while creating workspace. Please try again.", }); }); }; useEffect( () => () => { // when the component unmounts set the default values to whatever user typed in setDefaultValues(getValues()); }, [getValues, setDefaultValues] ); return (
Workspace name setValue("slug", e.target.value.toLocaleLowerCase().trim().replace(/ /g, "-")) } validations={{ required: "Workspace name is required", }} placeholder="e.g. My Workspace" error={errors.name} />
Workspace URL
https://app.plane.so/
{slugError && ( Workspace URL is already taken! )}
How large is your company
( {COMPANY_SIZE?.map((item) => ( {item.label} ))} )} /> {errors.company_size && ( {errors.company_size.message} )}
{isSubmitting ? "Creating..." : "Create Workspace"}
); };