I just followed a youtube tutorial about using server action with useFormState
. When I following the video, There is an error fro react saying to use useActionState
insted of useFormState
. So I followed it up. Here is my current implementation
// actions.ts
"use server";
export const createItem = async (
prevState: FormState,
data: FormData
): Promise<FormState> => {
const formData = Object.fromEntries(data.entries());
const parsed = ConfigSchema.safeParse(formData);
if (!parsed.success) {
return {
...prevState,
message: "failed",
success: false,
};
}
return {
image: "https://picsum.photos/200/200",
message: "success",
success: true,
};
};
// components.tsx
export const Step3 = () => {
const step3 = useOrderStore((state) => state.step3);
const formRef = React.useRef<HTMLFormElement>(null);
const [state, formAction, isPending] = React.useActionState(createItem, {
message: "",
image: "",
success: false,
});
console.log({ state, isPending });
const configForm = useForm<IItemConfig>({
resolver: zodResolver(ConfigSchema),
defaultValues: step3,
});
return (
<Card>
<CardContent className="flex gap-8 lg:flex-row flex-col">
<Form {...configForm}>
<form
className="order-3 lg:order-1"
action={formAction}
ref={formRef}
onSubmit={configForm.handleSubmit(() => formRef.current?.submit())}
>
<div className="space-y-4 w-full">
<FormField
control={configForm.control}
name="shape"
render={({ field }) => (
<FormItem>
<FormLabel>Bentuk Dasar</FormLabel>
<Select
{...field}
defaultValue={field.value}
onValueChange={field.onChange}
>
<SelectTrigger data-testid="font-family-select">
<SelectValue />
</SelectTrigger>
<SelectContent>
{SHAPE_OPTIONS.map((shape) => (
<SelectItem key={shape.value} value={shape.value}>
{shape.label}
</SelectItem>
))}
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full">
Generate
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
);
};
Whenever I tried to submit, I will got error
Uncaught Error: A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you're trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().
I’ve tried to change using requestSubmit()
but the form not submitted although the error is gone. Can someone help me pointed out the problem? thanks
I’ve tried to change using requestSubmit()
but the form not submitted although the error is gone. Can someone help me pointed out the problem? thanks
2
Answers
I’m not sure where some of the components you import come from, but try checking and following my instructions below.
react-hook-form: i am using version 7.52.1
try remove
<Form {...configForm}>
and</Form>
change
`
`
to
`
Please check the following:
form.submit()
withform.requestSubmit()
.