import React, { useEffect } from "react"; import useSWR, { mutate } from "swr"; // react-hook-form import { Controller, useFieldArray, useForm } from "react-hook-form"; // services import workspaceService from "services/workspace.service"; import userService from "services/user.service"; // hooks import useToast from "hooks/use-toast"; // ui import { CustomSelect, Input, PrimaryButton, SecondaryButton } from "components/ui"; // icons import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; // types import { ICurrentUserResponse, IWorkspace, OnboardingSteps } from "types"; // fetch-keys import { CURRENT_USER, USER_WORKSPACE_INVITATIONS } from "constants/fetch-keys"; // constants import { ROLE } from "constants/workspace"; type Props = { workspace: IWorkspace | undefined; user: ICurrentUserResponse | undefined; stepChange: (steps: Partial) => Promise; }; type EmailRole = { email: string; role: 5 | 10 | 15 | 20; }; type FormValues = { emails: EmailRole[]; }; export const InviteMembers: React.FC = ({ workspace, user, stepChange }) => { const { setToastAlert } = useToast(); const { control, handleSubmit, formState: { isSubmitting, errors }, } = useForm(); const { fields, append, remove } = useFieldArray({ control, name: "emails", }); const { data: invitations } = useSWR(USER_WORKSPACE_INVITATIONS, () => workspaceService.userWorkspaceInvitations() ); const nextStep = async () => { if (!user || !invitations) return; const payload: Partial = { workspace_invite: true, }; // update onboarding status from this step if no invitations are present if (invitations.length === 0) { payload.workspace_join = true; mutate( CURRENT_USER, (prevData) => { if (!prevData) return prevData; return { ...prevData, is_onboarded: true, }; }, false ); await userService.updateUserOnBoard({ userRole: user.role }, user); } await stepChange(payload); }; const onSubmit = async (formData: FormValues) => { if (!workspace) return; const payload = { ...formData }; await workspaceService .inviteWorkspace(workspace.slug, payload, user) .then(async () => { setToastAlert({ type: "success", title: "Success!", message: "Invitations sent successfully.", }); await nextStep(); }) .catch((err) => console.log(err)); }; const appendField = () => { append({ email: "", role: 15 }); }; useEffect(() => { if (fields.length === 0) { append([ { email: "", role: 15 }, { email: "", role: 15 }, { email: "", role: 15 }, ]); } }, [fields, append]); return (
{ if (e.code === "Enter") e.preventDefault(); }} >

Invite people to collaborate

Co-workers Email
Role
{fields.map((field, index) => (
( <> {errors.emails?.[index]?.email && ( {errors.emails?.[index]?.email?.message} )} )} />
( {ROLE[value]}} onChange={onChange} width="w-full" input > {Object.entries(ROLE).map(([key, value]) => ( {value} ))} )} />
{fields.length > 1 && ( )}
))}
{isSubmitting ? "Sending..." : "Send Invite"} Skip this step
); };