Skip to content

applyFromFormData()

ts
function applyFromFormData<T>(
   form: HTMLFormElement, 
   existing: T, 
   intercept: (key: string, value: FormDataEntryValue) => unknown): undefined | T;

Naive application or creation of form data to a given object. Updates (or creates) an object from the data of the given form.

Type Parameters

T

T extends object

Parameters

form

HTMLFormElement

form element to read data from

existing

T = ...

eventually existing data object to update

intercept

(key: string, value: FormDataEntryValue) => unknown

function to intercept and modify the key-value pairs before applying them

Returns

undefined | T

the updated / created data object

Examples

Read data from form as an object.

html
<form>
  <input name="name" value="John">
  <input name="age" value="30">
</form>
ts
const form = document.querySelector('form');
const data = applyFromFormData(form);
console.log(data);
{ name: 'John', age: '30' }

Update existing data object with form data.

html
<form>
  <input name="name" value="John">
  <input name="age" value="30">
</form>
ts
const existing = { gender: 'male', name: 'Peter' };
const updated = applyFromFormData(form, existing);
console.log(updated);
{ gender: 'male', name: 'John', age: '30' }

Manipulate form data before applying it.

html
<form>
  <input name="name" value="John">
  <input name="age" value="30">
</form>
ts
const existing = { name: 'Peter', age: 25 };
const updated = applyFromFormData(form, existing, (k, v) => k === 'age' ? parseInt(v as string, 10) : v);
console.log(updated);
{ gender: 'male', name: 'John', age: 30 }