Skip to content

Commit 2803746

Browse files
committed
Fix form submission using form ref and requestSubmit method
1 parent 7199ecb commit 2803746

2 files changed

Lines changed: 23 additions & 9 deletions

File tree

components/edit-car-button.tsx

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,12 @@ export function EditCarButton({ car }: EditCarButtonProps) {
3636
}
3737
}
3838

39-
const handleSubmit = () => {
40-
formRef.current?.submit()
39+
const handleSubmit = async () => {
40+
try {
41+
await formRef.current?.submit()
42+
} catch (error) {
43+
console.error('Error submitting form:', error)
44+
}
4145
}
4246

4347
return (

components/edit-car-form.tsx

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod"
44
import { useForm } from "react-hook-form"
55
import { useRouter } from "next/navigation"
66
import * as z from "zod"
7-
import { useState, useEffect, useImperativeHandle, forwardRef } from "react"
7+
import { useState, useEffect, useImperativeHandle, forwardRef, useCallback, useRef } from "react"
88
import Image from "next/image"
99
import { 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

Comments
 (0)