skip to Main Content

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


  1. I’m not sure where some of the components you import come from, but try checking and following my instructions below.

    1. react-hook-form: i am using version 7.52.1

    2. try remove <Form {...configForm}> and </Form>

    3. change

    `

    onSubmit={configForm.handleSubmit(() => formRef.current?.submit())}
    

    `

    to

    onSubmit={configForm.handleSubmit(data => onSubmit(data))}
    
    1. add new function onSubmit like this (before return)

    `

    const onSubmit = async (formdata:any) => {
      console.log(formdata);
    }
    
    Login or Signup to reply.
  2. Please check the following:

    • Replace form.submit() with form.requestSubmit().
    • Ensure that you are passing the form’s submit action correctly.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search