@modular-forms/react
Version:
The modular and type-safe form library for React
27 lines (26 loc) • 980 B
JavaScript
import { batch } from '@preact/signals-react';
import { initializeFieldStore, updateFieldDirty, validateIfRequired, } from '../utils';
export function setValue(form, name, value, { shouldTouched = true, shouldDirty = true, shouldValidate = true, shouldFocus = true, } = {}) {
batch(() => {
// Initialize store of specified field
const field = initializeFieldStore(form, name);
// Set new value
field.value.value = value;
// Update touched if set to "true"
if (shouldTouched) {
field.touched.value = true;
form.touched.value = true;
}
// Update dirty if set to "true"
if (shouldDirty) {
updateFieldDirty(form, field);
}
// Validate if set to "true" and necessary
if (shouldValidate) {
validateIfRequired(form, field, name, {
on: ['touched', 'change'],
shouldFocus,
});
}
});
}