Search code examples
javascriptreactjsredux-formformikreact-final-form

Should we store raw or parsed values in the form state


Intro:

  • we are using formik or final-form as a form manager in react
  • we get entity from API
  • we need to map that entity to edit form values

Case 1:

  • entity has an ISO date property
  • we use a date-picker whose onChange returns a JS date object

What should we store in form state: ISO date (String) or JS date (Object)?

If we store ISO date, parsing must be done in onChange handler.

Case 2:

  • entity has a boolean property
  • we use select element whose onChange returns a string

What should we store in form state: true (Boolean) or "true" (String)?


The general question is this: What to store in the form state?

Raw onChange values which can be parsed when they are used?

Or it is better to assure that date-pickers always return ISO date or undefined, that boolean fields always return Boolean or undefined, etc.


Solution

  • I think it really doesn't matter that much. With my libs, redux-form and final-form, there are parse/format functions to manage the conversion to and from form state. You can use those, and then not have to convert it upon submission, or keep it in the structure that your input component wants until submission and then convert it. I suppose the latter would technically be faster, as it would not require two conversions on every change.

    I often use react-rte, a wysiwyg editor, and convert the raw format to markdown in the form state on every keypress and it's plenty fast, so... I think it's just up to what feels more right to you. ⚖️