Add field to formData with React-hook-form
Unanswered
Atlantic menhaden posted this in #help-forum
Atlantic menhadenOP
Hello, I want to if it is possible to add a field to formData before submitting to server action with React-hook-form when the value is set outside the form ?
2 Replies
How about a hidden <input />?
Atlantic menhadenOP
Hello,
Thanks for your answer. I tried a lot a thing.
My goal was to upload an url (from a form) and an image (from outside the form) copied from clipboard via a server action.
Here is how I did, I will not explain the code unless someone ask. 🙂
Thanks for your answer. I tried a lot a thing.
My goal was to upload an url (from a form) and an image (from outside the form) copied from clipboard via a server action.
Here is how I did, I will not explain the code unless someone ask. 🙂
const [image, setImage] = useState<string>('')
const form = useForm<FormValues>({
resolver: zodResolver(uploadSchema),
defaultValues: {
url: '',
image: null,
},
})
const file = stringToBlob(image)
const tmp = new FormData()
tmp.append('url', form.getValues('url'))
if (file) tmp.append('image', file)
const addScreenshotWithImage = addScreenshot.bind(null, tmp)
const [state, formAction] = useFormState(addScreenshotWithImage, initialState)
useEffect(() => {
const handlePaste = (e: ClipboardEvent) => {
const items = e.clipboardData?.items
if (!items) return
Array.from(items).forEach((item) => {
if (item.kind === 'file') {
const file = item.getAsFile()
if (file) {
const reader = new FileReader()
reader.onloadend = () => {
setImage(reader.result as string)
}
reader.readAsDataURL(file)
}
}
})
}
document.addEventListener('paste', handlePaste)
return () => {
document.removeEventListener('paste', handlePaste)
}
}, [])