react-use-form-state icon indicating copy to clipboard operation
react-use-form-state copied to clipboard

Added `formState.setFields` method to be able to update multiple fields at once

Open frontendr opened this issue 6 years ago • 2 comments

First of all, thank you very much for this great package! It's an absolute breeze to work with!

One thing I've been missing is the ability to set the values of multiple fields at once. One example for this is when the data is loaded from the server. Currently one must set each field individually in a loop and then all those fields are also marked as touched which is not the case then.

So there was a need to be able to set the values of fields in the state but also manage their touched and validity state and while we're at it we could also set errors.

Just setting values is simple:

const values = { name: "john" };
formState.setFields(values);

But to be able to change the touched or validity state or set errors a second options argument can be provided:

const values = { name: "" };
formState.setFields(values, {
  // mark all fields as not touched:
  touched: false
  // mark specific fields as invalid:
  validity: {
    name: false
  },
  // set errors:
  errors: {
    name: "this field is required"
  }
});

Actually setting the validity of a field to false when also providing an error for it is redundant so I took the liberty of marking fields for which errors are provided as invalid if and only if no validity option is passed.

The same goes for setting the validity of a field to true. If a field is valid then you probably don't want to show an error so those are cleared if and only if no errors option is passed.

I did my best to make this PR as complete as possible:

  • Added multiple tests
  • Updated the index.d.ts file. (Please check it because I'm no TypeScript expert!)
  • Updated the README.md.

Hope you appreciate it!

Kind regards, Johan

frontendr avatar Jul 02 '19 13:07 frontendr

Hi @wsmd,

Is there anything I can do for this issue? Just double checking just to make sure I'm not forgetting to do something :-)

frontendr avatar Sep 09 '19 12:09 frontendr

Yep, would love to see this merged!

markerikson avatar Sep 14 '20 13:09 markerikson