Skip to content

Computed fields ​

computeValue derives a field's value from the rest of the form data (e.g. a fullName computed from firstName + lastName). It is called as (data, rootData) - rootData is the top-level form even for fields nested in a group. Every adapter's MultiFieldInput re-evaluates it once per change, against the post-change data - it is not re-run to a fixed point, so avoid chaining computeValue fields into a cycle, and return a primitive or a stable reference (returning a fresh object/array each call defeats the render-skipping optimisation). In development, applyComputedValues warns when a computeValue chain does not converge in one pass.

ts
import { applyComputedValues } from '@dynamic-field-kit/core';

const fields: FieldDescription[] = [
  { name: 'firstName', type: 'text' },
  { name: 'lastName', type: 'text' },
  {
    name: 'fullName',
    type: 'text',
    computeValue: (data) =>
      `${data.firstName ?? ''} ${data.lastName ?? ''}`.trim(),
  },
];

applyComputedValues(fields, { firstName: 'Ada', lastName: 'Lovelace' });
// => { firstName: 'Ada', lastName: 'Lovelace', fullName: 'Ada Lovelace' }

Adapters call applyComputedValues for you whenever MultiFieldInput's data changes; you normally only need to import it directly when working with form data outside of a component (e.g. on submit).

Released under the MIT License.