Search code examples
javascriptreactjsvalidationreact-hooksreact-hook-form

how to only submit data change in react hook form


I am using the 'editData' function to send an API request, and I am using React Hook Form. However, React Hook Form sends all fields when I submit the form. I only want to send the fields that have changed. How can I achieve this? Thank you for your assistance


Solution

  • RHF maintains a dirtyFields form state that you can compare your form values against to filter out unmodified fields.

    There are several ways to do this, but here's one:

    // Map RHF's dirtyFields over the `data` received by `handleSubmit` and return the changed subset of that data.
    export function dirtyValues(dirtyFields: object | boolean, allValues: object): object {
      // If *any* item in an array was modified, the entire array must be submitted, because there's no way to indicate
      // "placeholders" for unchanged elements. `dirtyFields` is `true` for leaves.
      if (dirtyFields === true || Array.isArray(dirtyFields))
        return allValues;
      // Here, we have an object
      return Object.fromEntries(Object.keys(dirtyFields).map(key => [key, dirtyValues(dirtyFields[key], allValues[key])]));
    }
    

    This is an accepted answer from a related GitHub discussion you can find here