Replies: 2 comments
|
I would not put every upload detail into React Hook Form state. The pattern I usually use is:
So the form value might be something stable like: type FormValues = {
title: string
attachments: Array<{
key: string
url: string
name: string
size: number
}>
}Then the upload field component can own its internal async state, but still write the successful result into RHF: function AttachmentField() {
const { setValue, setError, clearErrors, watch } = useFormContext<FormValues>()
const attachments = watch('attachments') ?? []
const [pending, setPending] = useState(0)
async function onFiles(files: FileList) {
setPending((n) => n + files.length)
try {
const uploaded = await uploadFilesToS3(files)
setValue('attachments', [...attachments, ...uploaded], {
shouldDirty: true,
shouldValidate: true,
})
clearErrors('attachments')
} catch (e) {
setError('attachments', {
type: 'upload',
message: 'Upload failed. Please retry.',
})
} finally {
setPending((n) => n - files.length)
}
}
return /* input + progress UI */
}You do not have to lift all upload state to the component that owns For submit blocking, I would combine two checks:
If multiple fields need to know whether any upload is pending, use a tiny colocated store/context for upload status. But I would still keep RHF focused on serializable, submitted values. That keeps dirty state, reset, validation, and submission much easier to reason about. |
|
Keeping progress/retries in the upload component and completed file metadata in RHF makes sense. Two things I'd change in the example above: Read the latest attachments after the upload finishes. The const uploaded = await uploadFilesToS3(files);
const current = getValues('attachments') ?? [];
setValue('attachments', [...current, ...uploaded], {
shouldDirty: true,
shouldValidate: true,
});Take Gate submission in the handler, not just the button. A small upload context can expose Also avoid blindly calling |
Uh oh!
There was an error while loading. Please reload this page.
I'm looking for recommendations on the best way to manage asynchronous file upload state in a complex form.
Context
My setup looks like this:
<input type="file">.Questions
I'm mainly interested in understanding the recommended architecture and trade-offs for this scenario, especially when the upload logic is only one piece of a much larger form.
All reactions