React-redux-form: Submit only changed fields?

Created on 20 Sep 2016  路  2Comments  路  Source: davidkpiano/react-redux-form

Anyway to submit only changed fields on a form?

Additionally, right now my form passes the entire model to the submit handler, even if the form only uses a couple of fields from that model. Naturally, I can shave my model down after it's returned from the server to be more appropriately sized but it would be nice to be able to simply grab the current field values from the form, rather than the entire model.

Why's this important? Well, our app currently uses a relatively large object in state to populate several components on the page (a couple of status components, a name and headline h1 and h2, a few action buttons that rely on this object for their state/visibility etc.). Rather than duplicate parts of that object over our state tree, it would be helpful for our form to directly address it. So when the user updates the "name" or "headline" fields in the form, we only have to dispatch an action to update that object and not the original one plus the cut down one being used in the form.

Edit:

Summary of requested enhancements:

  1. Forms only submit model elements being used in fields.
  2. Forms only submit changed model elements.
enhancement

Most helpful comment

That would make for a good enhancement! I'll add it after releasing V1.

All 2 comments

That would make for a good enhancement! I'll add it after releasing V1.

To avoid adding too much bloat to the library, I feel that this is better solved in userland. Here's the general strategy:

  1. Upon successful submit, save the current form's value to

    • internal component state

    • the Redux store state, using a custom reducer

  2. In the function passed to onSubmit, you can check the diff:
function getDiff(previousValues, currentValues) {
  // either implement this yourself
  // or use a library
}

handleSubmit(values) {
  const { lastSubmittedValues = {} } = this.state;

  const diff = getDiff(lastSubmittedValues, values);

  const promise = myAPI.patch('user', diff); // some promise

  this.props.dispatch(actions.submit('user', promise));
}

The reason for this is that a proper object/array diffing implementation can be significantly verbose and/or opinionated (think: shallow vs. deep nth-level vs. recursive diffs, array order matters/doesn't matter, etc.).

Was this page helpful?
0 / 5 - 0 ratings