- Docs
- Serialize the form with getData()
Serialize the form with getData()
Returns the form serialized as both a plain object and a fresh FormData instance. Empty file inputs are filtered out.
Returns the form serialized as both a plain object and a fresh FormData instance. Empty file inputs are filtered out.
Signature
getData(): SerializedFormResult
interface SerializedFormResult {
data: Record<string, SerializedFormValue>
formData: FormData
}
Parameters
None.
Returns
data— plain object mirror of the form. Repeated names become arrays. Strings andFileinstances are preserved as-is.formData— a freshFormDatainstance, safe to send directly tofetch.
Behaviour
- Reads directly from the live DOM via
new FormData(formElement). - Drops entries where the value is an empty
File(size === 0andname === '') — these are produced by empty<input type="file">controls. - Builds the
datamirror while iterating the rawFormData, grouping repeated names into arrays.
Examples
Send to a JSON endpoint
import { form } from '@samline/forms'
const contact = form('contact-form')
contact.onSubmit(async (_element, data) => {
await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
})
Send a real FormData to a file-upload endpoint
import { form } from '@samline/forms'
const upload = form('upload-form')
upload.onSubmit(async (_element, _data, formData) => {
await fetch('/api/upload', { method: 'POST', body: formData })
})
Snapshot the form state without submitting
const profile = form('profile-form')
profile.subscribe(state => {
if (state.submitCount > 0) {
const { data } = profile.getData()
console.log('last submit payload:', data)
}
})
Edge cases
- Empty file inputs are filtered out of both
dataandformData. This is intentional — HTML produces placeholderFileentries when a file input is rendered but no file is selected. - The returned
datamirror is fresh on every call. Safe to mutate. getData()does not trigger validation, watchers, or autoSubmit — it is a pure read.- The plain object form is convenient for JSON endpoints; the
FormDataform is required for file uploads. Browsers will not serializeFileinstances into JSON.
Related
parseFormData— same serializer, used directly without a controller.getValue— read a single field’s value.onSubmit— receives the same shape as arguments.format— when a field is formatted, theFormDatacarries both the canonical name (with the raw value) and the<field>_displayedname (with the formatted value). See the mirror convention.