MCPcopy Create free account
hub / github.com/react-hook-form/react-hook-form / _reset

Function _reset

src/logic/createFormControl.ts:1492–1633  ·  view source on GitHub ↗
(
    formValues,
    keepStateOptions = {},
  )

Source from the content-addressed store, hash-verified

1490 };
1491
1492 const _reset: UseFormReset<TFieldValues> = (
1493 formValues,
1494 keepStateOptions = {},
1495 ) => {
1496 const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1497 const cloneUpdatedValues = cloneObject(updatedValues);
1498 const isEmptyResetValues = isEmptyObject(formValues);
1499 const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
1500
1501 if (!keepStateOptions.keepDefaultValues) {
1502 _defaultValues = updatedValues;
1503 }
1504
1505 if (!keepStateOptions.keepValues) {
1506 if (keepStateOptions.keepDirtyValues) {
1507 const fieldsToCheck = new Set([
1508 ..._names.mount,
1509 ...Object.keys(getDirtyFields(_defaultValues, _formValues)),
1510 ]);
1511 for (const fieldName of Array.from(fieldsToCheck)) {
1512 const isDirty = get(_formState.dirtyFields, fieldName);
1513 const existingValue = get(_formValues, fieldName);
1514 const newValue = get(values, fieldName);
1515
1516 if (isDirty && !isUndefined(existingValue)) {
1517 set(values, fieldName, existingValue);
1518 } else if (!isDirty && !isUndefined(newValue)) {
1519 setValue(fieldName as FieldPath<TFieldValues>, newValue);
1520 }
1521 }
1522 } else {
1523 if (isWeb && isUndefined(formValues)) {
1524 for (const name of _names.mount) {
1525 const field = get(_fields, name);
1526 if (field && field._f) {
1527 const fieldReference = Array.isArray(field._f.refs)
1528 ? field._f.refs[0]
1529 : field._f.ref;
1530
1531 if (isHTMLElement(fieldReference)) {
1532 const form = fieldReference.closest('form');
1533 if (form) {
1534 form.reset();
1535 break;
1536 }
1537 }
1538 }
1539 }
1540 }
1541
1542 if (keepStateOptions.keepFieldsRef) {
1543 for (const fieldName of _names.mount) {
1544 setValue(
1545 fieldName as FieldPath<TFieldValues>,
1546 get(values, fieldName),
1547 );
1548 }
1549 } else {

Callers 1

resetFunction · 0.85

Calls 4

cloneObjectFunction · 0.85
getDirtyFieldsFunction · 0.85
setValueFunction · 0.85
deepEqualFunction · 0.85

Tested by

no test coverage detected