Search code examples
javascriptformsreactjsredux-form

redux-form - Submit only edited field


In this example, I have a form to update user information and it is written in React with redux-form 6.5. I'm a newbie with this stack.

The render form function is like:

render() {
    const { handleSubmit } = this.props;        
    return (
      <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
        <Field name="name" component="input" type="text"/>
        <Field name="surname" component="input" type="text"/>
        <button action="submit">Sign in</button>
      </form>
    );

I have the reduxForm connection:

const extendedComponent = reduxForm({
  form: 'userdetail',
  validate
})(UserDetail);

And I have submit handler:

 handleFormSubmit(user) {
    // TODO: how can I get only the touched fields?
    this.props.updateUser(user);
  }

I receive correctly the object user after the validation, I send the PUT call and everything works fine.

But I don't like to send all the data in the PUT, my wish is to send only the edited data to the PUT. I understand that I could retrieve the initialValues and compare all fields.

There is another way? How can I get only the touched fields?

Which is the best practice to do this?

It seems to me a common task and I'm not finding anything about that, so I am assuming I'm completely missing the point.

Thank you all :)


Solution

  • According to the maintainer of the redux-form project: "That's not a feature of the library".

    In that response, he recommends handling the diffing yourself or using a pre-existing library, like object-diff.

    For example like this:

    import diff from 'object-diff'
    
    handleFormSubmit(user, dispatch, props) {
      const { initialValues } = props 
      const changedValues = diff(initialValues, user)
      this.props.updateUser(changedValues);
    }