UNPKG

@modular-forms/qwik

Version:

The modular and type-safe form library for Qwik

52 lines (51 loc) 1.99 kB
import { getUniqueId } from './getUniqueId'; import { setFieldArrayState } from './setFieldArrayState'; import { setFieldState } from './setFieldState'; /** * Sets the specified field array value to the corresponding field and field * array stores. * * @param form The form of the field array. * @param name The name of the field array. * @param options The value options. */ export function setFieldArrayValue(form, name, { at: index, value }) { // Create recursive function to update stores const updateStores = (prevPath, data) => { Object.entries(data).forEach(([path, value]) => { // Create new compound path const compoundPath = `${prevPath}.${path}`; // If it is a field array, update field array store if (form.internal.fieldArrayPaths?.includes(compoundPath.replace(/.\d+./g, '.$.'))) { const items = value.map(() => getUniqueId()); setFieldArrayState(form, compoundPath, { startItems: [...items], items, error: '', touched: false, dirty: false, }); // If it is a field, update field store } else if (!value || typeof value !== 'object' || Array.isArray(value) || value instanceof Date || value instanceof Blob) { setFieldState(form, compoundPath, { startValue: value, value, error: '', touched: false, dirty: false, }); } // If it is an object or array, update nested stores if (value && typeof value === 'object') { updateStores(compoundPath, value); } }); }; // Update store of field array index updateStores(name, { [index]: value }); }