ui icon indicating copy to clipboard operation
ui copied to clipboard

Submit function not triggering 🙏 Please help 🙏

Open aymanechaaba1 opened this issue 2 years ago • 35 comments

export const contactFormSchema = z.object({
  id: z.string().cuid().optional(),
  created_at: z.date().optional(),
  updated_at: z.date().optional(),
  email: z.string().email(),
  phone: z.string().min(10).max(14),
  name: z.string().min(3).max(10),
  relationship: z.string(),
  avatar: z.instanceof(File).optional(),
  student_id: z.string().cuid(),
});
'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

function useCustomForm({ formSchema }: { formSchema: any }) {
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {},
  });

  return [form];
}

export default useCustomForm;
const [form] = useCustomForm({
    formSchema: contactFormSchema,
  });

function onSubmit(values: z.infer<typeof contactFormSchema>) {
    console.log(values);
  }
<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="[email protected]" {...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>

aymanechaaba1 avatar Nov 05 '23 13:11 aymanechaaba1

I think its because of ur using 2 form controler

Use Form or form ..

This issue is not about shadcnUI i think

thareekanvar avatar Nov 06 '23 05:11 thareekanvar

@thareekanvar that's what's in the docs. it uses Form and form It worked for me in my first form, but this second one doesn't get triggered

aymanechaaba1 avatar Nov 06 '23 11:11 aymanechaaba1

They just mentioned OR so u have to use one form

thareekanvar avatar Nov 06 '23 11:11 thareekanvar

@thareekanvar Can you please give me a screenshot where they're mentioning that

aymanechaaba1 avatar Nov 06 '23 11:11 aymanechaaba1

image

You see this ..

thareekanvar avatar Nov 06 '23 11:11 thareekanvar

@thareekanvar It doesn't work, shadcn uses both

aymanechaaba1 avatar Nov 06 '23 12:11 aymanechaaba1

@thareekanvar wanna jump in into the code?

aymanechaaba1 avatar Nov 06 '23 12:11 aymanechaaba1

My real qs is why u using two form .. you can use one and go with it ..

thareekanvar avatar Nov 06 '23 12:11 thareekanvar

It didn't work my friend, I have tried what u said, I hope it did

aymanechaaba1 avatar Nov 06 '23 12:11 aymanechaaba1

I can help you .. give me something to contact you

thareekanvar avatar Nov 06 '23 12:11 thareekanvar

Brother now im in office give me a 1 hour i will be back in home ..

thareekanvar avatar Nov 06 '23 12:11 thareekanvar

@thareekanvar I just sent u an invitation, join my repo and work on ur branch (it has ur name)

aymanechaaba1 avatar Nov 06 '23 12:11 aymanechaaba1

@thareekanvar Take ur time, join me when u get back home

aymanechaaba1 avatar Nov 06 '23 12:11 aymanechaaba1

@thareekanvar You can't login?

aymanechaaba1 avatar Nov 06 '23 15:11 aymanechaaba1

@thareekanvar You can't login?

No i cant

thareekanvar avatar Nov 06 '23 16:11 thareekanvar

@aymanechaaba1 Make sure you aren't getting any errors, before you submit.

adeludedperson avatar Nov 06 '23 17:11 adeludedperson

Screenshot 2023-11-06 at 5 44 50 PM These are the logs I'm getting, but that doesn't affect the submit functionality, I hope so.

aymanechaaba1 avatar Nov 06 '23 17:11 aymanechaaba1

Screenshot 2023-11-06 at 5 44 50 PM These are the logs I'm getting, but that doesn't affect the submit functionality, I hope so.

I'm talking about form errors, you can check by accessing form.formState.errors

adeludedperson avatar Nov 07 '23 04:11 adeludedperson

You can check this its one of my working example code using with shadcn ui but im uaing formik for form validation that is the difference


import { useEffect, useState } from "react";

import { mutateFetcher } from "@/utils/query";
import { useMutation } from "@tanstack/react-query";
import { useFormik } from "formik";

import { cn } from "@/lib/utils";
import { Button } from "../../../ui/button";
import { Icons } from "../../../ui/icons";
import { Input } from "../../../ui/input";
import { Label } from "../../../ui/label";
import { toast } from "@/components/ui/use-toast";

interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {}

export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
  const { mutate, isLoading, error, data } = useMutation({
    mutationFn: (data) => {
      return mutateFetcher("/api/auth/signin", data);
    },
  });

  useEffect(() => {
    if (error) {
      toast({
        title: "Authentication error",
        description: `${error}`,
      });
    }

    if (data) {
      toast({
        title: "Authentication successful",
        description: "Check your email",
      });
    }
  }, [error, data]);

  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    onSubmit: (values) => {
      //@ts-ignore
      mutate(values);
    },
  });

  return (
    <div className="lg:p-8 flex flex-col justify-center items-center h-full">
      <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
        <div className="flex flex-col space-y-2 text-center">
          <h1 className="text-2xl font-semibold tracking-tight">Sign in</h1>
        </div>
        <div className={cn("grid gap-6", className)} {...props}>
          <form onSubmit={formik.handleSubmit}>
            <div className="grid gap-2">
              <div className="grid gap-1">
                <Label className="sr-only" htmlFor="email">
                  Email
                </Label>
                <Input
                  id="email"
                  name="email"
                  placeholder="[email protected]"
                  type="email"
                  autoCapitalize="none"
                  autoComplete="email"
                  autoCorrect="off"
                  disabled={isLoading}
                  onChange={formik.handleChange}
                  value={formik.values.email}
                />
              </div>
              <div className="grid gap-1">
                <Label className="sr-only" htmlFor="email">
                  Password
                </Label>
                <Input
                  id="password"
                  name="password"
                  placeholder="*******"
                  type="password"
                  disabled={isLoading}
                  onChange={formik.handleChange}
                  value={formik.values.password}
                />
              </div>
              <Button disabled={isLoading}>
                {isLoading && (
                  <Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
                )}
                Sign In with Email
              </Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
} ```

thareekanvar avatar Nov 07 '23 05:11 thareekanvar

You can check this its one of my working example code using with shadcn ui but im uaing formik for form validation that is the difference


import { useEffect, useState } from "react";

import { mutateFetcher } from "@/utils/query";
import { useMutation } from "@tanstack/react-query";
import { useFormik } from "formik";

import { cn } from "@/lib/utils";
import { Button } from "../../../ui/button";
import { Icons } from "../../../ui/icons";
import { Input } from "../../../ui/input";
import { Label } from "../../../ui/label";
import { toast } from "@/components/ui/use-toast";

interface UserAuthFormProps extends React.HTMLAttributes<HTMLDivElement> {}

export function UserAuthForm({ className, ...props }: UserAuthFormProps) {
  const { mutate, isLoading, error, data } = useMutation({
    mutationFn: (data) => {
      return mutateFetcher("/api/auth/signin", data);
    },
  });

  useEffect(() => {
    if (error) {
      toast({
        title: "Authentication error",
        description: `${error}`,
      });
    }

    if (data) {
      toast({
        title: "Authentication successful",
        description: "Check your email",
      });
    }
  }, [error, data]);

  const formik = useFormik({
    initialValues: {
      email: "",
      password: "",
    },
    onSubmit: (values) => {
      //@ts-ignore
      mutate(values);
    },
  });

  return (
    <div className="lg:p-8 flex flex-col justify-center items-center h-full">
      <div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[350px]">
        <div className="flex flex-col space-y-2 text-center">
          <h1 className="text-2xl font-semibold tracking-tight">Sign in</h1>
        </div>
        <div className={cn("grid gap-6", className)} {...props}>
          <form onSubmit={formik.handleSubmit}>
            <div className="grid gap-2">
              <div className="grid gap-1">
                <Label className="sr-only" htmlFor="email">
                  Email
                </Label>
                <Input
                  id="email"
                  name="email"
                  placeholder="[email protected]"
                  type="email"
                  autoCapitalize="none"
                  autoComplete="email"
                  autoCorrect="off"
                  disabled={isLoading}
                  onChange={formik.handleChange}
                  value={formik.values.email}
                />
              </div>
              <div className="grid gap-1">
                <Label className="sr-only" htmlFor="email">
                  Password
                </Label>
                <Input
                  id="password"
                  name="password"
                  placeholder="*******"
                  type="password"
                  disabled={isLoading}
                  onChange={formik.handleChange}
                  value={formik.values.password}
                />
              </div>
              <Button disabled={isLoading}>
                {isLoading && (
                  <Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
                )}
                Sign In with Email
              </Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
} ```

formik and react-hook-form are used differently

adeludedperson avatar Nov 07 '23 05:11 adeludedperson

You only one form componente i think ise

it will work i think .

I checked ur package

thareekanvar avatar Nov 07 '23 05:11 thareekanvar

You only one form componente i think ise

it will work i think . I checked ur package

The problem isn't using two form components, one is from react-hook-form library which wraps html's <form> tag, most prolly the problem is within zod schema validation.

adeludedperson avatar Nov 07 '23 05:11 adeludedperson

thats will be also a reason .. so he has to console the form errors so he can understand its schema validation error or not

thareekanvar avatar Nov 07 '23 05:11 thareekanvar

yeah

adeludedperson avatar Nov 07 '23 05:11 adeludedperson

Also i think u have to use FormProvider not Form

thareekanvar avatar Nov 07 '23 05:11 thareekanvar

Screenshot 2023-11-07 at 11 29 46 AM

Nope, it is Form, exported from shadcn/ui Form component.

adeludedperson avatar Nov 07 '23 06:11 adeludedperson

Ok i think he using from form package .. my bad sorry

thareekanvar avatar Nov 07 '23 06:11 thareekanvar

@thareekanvar You have access to the code?

aymanechaaba1 avatar Nov 07 '23 10:11 aymanechaaba1

@ShaikRehan123 I'm not getting any errors

aymanechaaba1 avatar Nov 07 '23 10:11 aymanechaaba1

@ShaikRehan123 I get no validation errors

aymanechaaba1 avatar Nov 07 '23 10:11 aymanechaaba1