@@ -4,7 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod"
44import { useForm } from "react-hook-form"
55import { useRouter } from "next/navigation"
66import * as z from "zod"
7- import { useState , useEffect , useImperativeHandle , forwardRef } from "react"
7+ import { useState , useEffect , useImperativeHandle , forwardRef , useCallback , useRef } from "react"
88import Image from "next/image"
99import { X } from "lucide-react"
1010
@@ -62,12 +62,22 @@ export const EditCarForm = forwardRef<EditCarFormRef, EditCarFormProps>(
6262 } ,
6363 } )
6464
65+ const formRef = useRef < HTMLFormElement > ( null )
66+
6567 useImperativeHandle ( ref , ( ) => ( {
66- submit : ( ) => {
67- form . handleSubmit ( onSubmit ) ( )
68+ submit : async ( ) => {
69+ if ( formRef . current ) {
70+ formRef . current . requestSubmit ( )
71+ } else {
72+ const isValid = await form . trigger ( )
73+ if ( isValid ) {
74+ const values = form . getValues ( )
75+ await onSubmit ( values )
76+ }
77+ }
6878 } ,
6979 imageUrl,
70- } ) )
80+ } ) , [ form , imageUrl , onSubmit ] )
7181
7282 useEffect ( ( ) => {
7383 if ( car . imageUrl ) {
@@ -77,7 +87,7 @@ export const EditCarForm = forwardRef<EditCarFormRef, EditCarFormProps>(
7787 }
7888 } , [ car . imageUrl , onImageUrlChange ] )
7989
80- async function onSubmit ( values : FormValues ) {
90+ const onSubmit = useCallback ( async ( values : FormValues ) => {
8191 try {
8292 const response = await fetch ( `/api/cars/${ car . id } ` , {
8393 method : 'PATCH' ,
@@ -102,11 +112,11 @@ export const EditCarForm = forwardRef<EditCarFormRef, EditCarFormProps>(
102112 } catch ( error ) {
103113 console . error ( 'Error updating car:' , error )
104114 }
105- }
115+ } , [ car . id , imageUrl , router , onSuccess ] )
106116
107117 return (
108118 < Form { ...form } >
109- < form id = { formId } onSubmit = { form . handleSubmit ( onSubmit ) } className = "space-y-8 max-w-xl" >
119+ < form ref = { formRef } id = { formId } onSubmit = { form . handleSubmit ( onSubmit ) } className = "space-y-8 max-w-xl" >
110120 < FormField
111121 control = { form . control }
112122 name = "manufacturer"
0 commit comments