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
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
@New Guinea Freshwater Crocodile 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>
);
}
you can remove all the state stuff, if you don't need it yourself. Shadcn handles that for you. Your form then can be exclusive to be just a form. Single responsibility principle: Your form does not know about your dialog and just works fine
shadcn ui uses react-hook-form as I remember
to close the dialog when your form is submitted, expose a
to close the dialog when your form is submitted, expose a
onSubmit prop from form component and call it in handleSubmitNew 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.