Next.js Discord

Discord Forum

Is there a way to simplify how I'm doing this Form in a Dialog?

Unanswered
New Guinea Freshwater Crocodile posted this in #help-forum
Open in Discord
New Guinea Freshwater CrocodileOP
I'm using shadcn and next14 with server actions:

const initialState = {
    success: false,
    message: "",
};

export function CreateToolDialog() {
    const [state, formAction] = useFormState(createTool, initialState);
    const [isOpen, setIsOpen] = useState(false);

    useEffect(() => {
        if (state.success) {
            setIsOpen(false);
        }
    }, [state]);

    const handleOpenChange = (open: boolean) => {
        setIsOpen(open);
        if (!open) {
            state.message = "";
        }
    };

    return (
        <Dialog open={isOpen} onOpenChange={handleOpenChange}>
            <DialogTrigger asChild>
                <Button variant="outline" onClick={() => setIsOpen(true)}>
                    Create tool
                </Button>
            </DialogTrigger>
             // Form here  
        </Dialog>
    );
}

4 Replies

shadcn ui uses react-hook-form as I remember
to close the dialog when your form is submitted, expose a onSubmit prop from form component and call it in handleSubmit
New Guinea Freshwater CrocodileOP
@fuma if I do this then I can't use server actions w/ useFormState hook to submit the form
It’s theoretically possible (a thread has discussed this in deep: https://github.com/react-hook-form/react-hook-form/issues/10391), although I personally use Route Handler for better DX. RHF is indeed useful for handling validation and form state management, but if you don’t mind to implement it from scratch, as far as I know there’s no way to simplify it.