"use client"; import clsx from "clsx"; import { ChangeEvent, useEffect, useRef, useState } from "react"; import { useFormState } from "react-dom"; import { Input } from "~/components/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "~/components/ui/select"; import { addSubRegion } from "~/server/actions/addSubRegion"; import SubmitButton from "../SubmitButton"; import { Check, CircleX } from "lucide-react"; type Region = { id: string; name: string; countryId: string; }; type Country = { id: string; name: string; }; export default function CreateSubRegionForm(props: { allRegions: Region[]; allCountries: Country[]; }) { const { allRegions, allCountries } = props; const [selectCountryId, setSelectCountryId] = useState( undefined, ); const [selectCountryRegions, setSelectCountryRegions] = useState( [], ); const [formState, formActions] = useFormState(addSubRegion, { message: "", errors: undefined, fieldValues: { name: "", regionId: "", }, }); useEffect(() => { if (selectCountryId) { const regions = allRegions.filter( (region) => region.countryId === selectCountryId, ); setSelectCountryRegions(regions); } }, [selectCountryId]); const formRef = useRef(null); useEffect(() => { if (formState.message === "success") { formRef.current?.reset(); } }, [formState.message]); return (
{/* country selector */}
{/* region selector */}
{formState.message === "success" && !formState.errors?.regionId ? ( ) : ( "" )} {formState.errors?.regionId ? (
{formState.errors?.regionId}
) : ( "" )}
{formState.message === "success" && !formState.errors?.name ? ( ) : ( "" )} {formState.errors?.name ? (
{formState.errors?.name}
) : ( "" )}
); }