Simple way to update form values depending on changes with react-final-form
Asked Answered
S

1

9

I'm trying to implement a form with two consecutive dependent Select with react-final-form and material-ui

Requirements

  • Both fields are required
  • When user selects a country value
    • city field should reset to blank
    • city field should not be marked as invalid
  • User should be able to reset the form completely anytime

I struggle to find a simple and elegant solution to this requirements with react-final-form API.

There may be approaches with mutators, react-final-form-listeners, or decorators but this seems to me like a common use case of forms for which a simple solution without advanced APIs would be nice.


Here is a version with a combination of FormSpy component, useRef hook and the form.reset api.

https://codesandbox.io/embed/react-final-form-material-ui-field-dependencies-hn7ps

  • subscribre to form values via FormSpy onChange prop
  • update a react ref each time values change
  • compare ref values with new values and use form.reset API to reset city field value without triggering validation

Here is another version using Declarating Form Rules approach via react-final-form-listeners like Erik adviced to do.

https://codesandbox.io/embed/react-final-form-material-ui-field-dependencies-ijxd0

It is a lot more simpler, as we dont need a react ref, and FormSpy.


Both solutions works almost perfectly except that the form.reset method redefines form initialValues under the hood, so that the RESET button do not reset form to the original initialValues anymore.

Is there a builtin way to hook in form state changes and compare old/new values ?

Spiniferous answered 21/6, 2019 at 9:31 Comment(1)
uoooo this solutions save me a lot of time. :-)Signe
K
4

Perhaps Declarative Form Rules are what you need?

Kinetics answered 22/6, 2019 at 15:35 Comment(6)
I'll give it a try and come back to you. Thank you for your prompt answer ErikSpiniferous
Here is a modified version with react-final-form-listeners : codesandbox.io/embed/… - I ended using this solution in my project, but please note the it still has the downside of modifying original initialValues.Spiniferous
@Spiniferous it seems not to load the proper city.Syreetasyria
@DimitriKopriwa not sure what you mean. The purpose of the sample is not to set the right city depending on the country you choose, but just to implement the requirements i described initially (reset the city field mainly)Spiniferous
I have another use case. I want to update state so that another component outside the form component knows that a particular value has changed. I tried formspy, but the moment I setState the whole component re-rendersLaunch
If you came here and thought "this might be the nice solution to my problem" note that the react-final-form-listeners is currently NOT working with react 18Behrens

© 2022 - 2024 — McMap. All rights reserved.