Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

form handle onsubmit not working #456

Closed
denimcodes opened this issue May 25, 2023 · 9 comments
Closed

form handle onsubmit not working #456

denimcodes opened this issue May 25, 2023 · 9 comments

Comments

@denimcodes
Copy link

the onSubmit function has log statement but it's not logging anything when submit button is clicked.

function MakeOfferForm() {
          const makeOfferFormSchema = z.object({
		offerAmount: z.coerce
			.number({
				required_error: "Offer amount is required",
				invalid_type_error: "Offer amount must be a number",
			})
			.min(1),
		duration: z.number().min(1).max(14),
	});

	type MakeOfferFormValues = z.infer<typeof makeOfferFormSchema>;

	const makeOfferForm = useForm<MakeOfferFormValues>({
		resolver: zodResolver(makeOfferFormSchema),
		defaultValues: {
			offerAmount: 0,
			duration: 0,
		},
	});

	function onSubmit(values: MakeOfferFormValues) {
		console.log(values);
	}

	return (
		<Form {...makeOfferForm}>
			<form onSubmit={makeOfferForm.handleSubmit(onSubmit)}>
				<FormField
					control={makeOfferForm.control}
					name="offerAmount"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Offer amount (SOL)</FormLabel>
							<FormControl>
								<Input {...field} type="number" step={0.01} />
							</FormControl>
							<FormMessage />
						</FormItem>
					)}
				/>
				<Button type="submit" className="mt-2">
					Confirm offer
				</Button>
			</form>
		</Form>
	);
}
@shadcn
Copy link
Collaborator

shadcn commented May 25, 2023

The onSubmit is only called when validation passes. You currently have validation errors.

In your schema, you've set a duration field but you don't have an actual field for it. So on submit, this is resulting into a required field/value missing.

If you log console.log(makeOfferForm.formState.errors) you should see the error.

What you can do here is:

  1. Add a FormField and render the duration field.
  2. Remove the duration field from the schema if not needed.
  3. Make it optional: duration: z.number().min(1).max(14).optional()

@aymanechaaba1
Copy link

Submit Button doesn't trigger

🙏 Please help @shadcn 🙏

<Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="secondary">Add Contact</Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Add Contact</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input placeholder="somename@gmail.com" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Phone</FormLabel>
                  <FormControl>
                    <Input placeholder="eg: 06 28 29 59 30" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Name</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="relationship"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Relationship</FormLabel>
                  <Select
                    onValueChange={field.onChange}
                    defaultValue={field.value}
                  >
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue placeholder="Select relationship" />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      <SelectItem value="mother">Mother</SelectItem>
                      <SelectItem value="father">Father</SelectItem>
                      <SelectItem value="brother">Brother</SelectItem>
                      <SelectItem value="sister">Sister</SelectItem>
                      <SelectItem value="uncle">Uncle</SelectItem>
                      <SelectItem value="aunt">Aunt</SelectItem>
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="avatar"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Avatar</FormLabel>
                  <FormControl>
                    <>
                      <Input
                        type="file"
                        accept="image/png, image/jpeg"
                        name="avatar"
                        onChange={(e) => {
                          if (e.target.files) {
                            field.onChange(e.target.files[0]);
                          }
                        }}
                      />
                      <ProgressBar
                        progress={progress}
                        setProgress={setProgress}
                      />
                    </>
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit">Submit</Button>
          </form>
        </Form>
      </DialogContent>
    </Dialog>

@salahbm
Copy link

salahbm commented Dec 28, 2023

Hello everyone : ), Could anyone solve this problem?

@dezoito
Copy link

dezoito commented Jan 26, 2024

@salahbm , were you able to fix this?

I'm experiencing the same issue (click on the submit button and nothing happens).

UPDATE:
This answer fixed it for me:
#709 (comment)

@salahbm
Copy link

salahbm commented Jan 27, 2024

@shadcn Yes, it was error related to z npm (zod package) , turns out I left some fields empty. If u are using the same pls check out the all the fields, and make sure they have initial value

@Higashi-Masafumi
Copy link

Higashi-Masafumi commented Jul 11, 2024

Click the button but does not work onSubmit.. don't happen anything and zod validation does not work. Why ?? Please help me !
`import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "../components/ui/ui/card";
import { Input } from "../components/ui/ui/input";
import { Button } from "../components/ui/button";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../components/ui/ui/form";
import { createClient } from "@supabase/supabase-js";
import { type ActionFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { createServerSupabaseClient } from "~/supabase.server";
import { useActionData, useNavigate, useSubmit } from "@remix-run/react";

const formSchema = z.object({
email: z.string()
.min(1, { message: "メールアドレスを入力してください" })
.email("有効なメールアドレスを入力してください"),
password: z.string()
.min(8, { message: "パスワードは8文字以上である必要があります" }),
});

export const action = async({ request }: ActionFunctionArgs) => {
const { supabase, headers } = await createServerSupabaseClient(request);

const formData = await request.formData();  
const email = formData.get("email") as string;
const password = formData.get("password") as string;

const { data, error } = await supabase.auth.signUp({
    email: email,
    password: password,
});

console.log(error);

if (error) {
    return json({ error: error.message }, { status: 400 });
return redirect("/");

}

export default function Register() {

const actionData = useActionData<{error?: string}>();
const navigate = useNavigate();

const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
        email: "",
        password: "",
    },
});

const onSubmit = async (formData: z.infer<typeof formSchema>) => {

    const supabase = createClient(process.env.VITE_SUPABASE_URL!, process.env.VITE_SUPABASE_ANON_KEY!);
    const { data, error } = await supabase.auth.signUp({
        email: formData.email,
        password: formData.password,
    });
    console.log(formData)
    console.log(data);
    console.log("amai");

    if (error) {
        form.setError("password", { message: error.message });
    }
        navigate("/");
    }
};

return (
    <div className="flex justify-center items-center min-h-screen">
        <Card>
            <CardHeader>
                <CardTitle>新規登録</CardTitle>
                <CardDescription>アカウントを作成してください</CardDescription>
            </CardHeader>
            <CardContent>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                        <FormField control={form.control} name="email" render={({ field }) => (
                            <FormItem>
                                <FormLabel>メールアドレスを入力してください</FormLabel>
                                <FormControl>
                                    <Input {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        <FormField control={form.control} name="password" render={({ field }) => (
                            <FormItem>
                                <FormLabel>パスワードを入力してください</FormLabel>
                                <FormControl>
                                    <Input type="password" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )} />
                        {actionData?.error && <p>{actionData.error}</p>}
                        <Button type="submit">新規登録</Button>
                    </form>
                </Form>
            </CardContent>
        </Card>
    </div>
);

}`

@Atabic
Copy link

Atabic commented Jul 18, 2024

Hey everyone, Ik the thread is closed but leaving it here so it can help someone:
Apart from any validation errors if you are still seeing no values on the console then you should verify that
Your fields in Formschema and default values should be completely rendered in the form as FormField
I had 10 fields and I was rendering only two, I had no validation errors but still was unable to see console.log(values)

@Simone-shalom
Copy link

Hey everyone, Ik the thread is closed but leaving it here so it can help someone: Apart from any validation errors if you are still seeing no values on the console then you should verify that Your fields in Formschema and default values should be completely rendered in the form as FormField I had 10 fields and I was rendering only two, I had no validation errors but still was unable to see console.log(values)

Had same issue - u have to render FormField's for all defined fields in schema, pin it

@GuilhermeSchwengber20
Copy link

Hey everyone, Ik the thread is closed but leaving it here so it can help someone: Apart from any validation errors if you are still seeing no values on the console then you should verify that Your fields in Formschema and default values should be completely rendered in the form as FormField I had 10 fields and I was rendering only two, I had no validation errors but still was unable to see console.log(values)

This is worked for me, thanks xD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

9 participants