Sync values between two fields #9841
Unanswered
chamatt
asked this question in
Show and tell
Replies: 1 comment
-
I'm wavering between The watch docs said |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I have an use-case in my forms where I want to partially sync one of the fields to another. Our specific case is a combo-field called MoneyInput which stores the currencyCode and the amount. We usually want to have a single field select the currency and then update all the other field to the same one and prevent them from being edited.
The two ways to do this are:
1 - Call setValue for all other field on onChange (good, but depending on how nested your fields are this may not be ergonomic)
2 - useEffect + useWatch and update the values of the other field in the root level of the form.
For the form I'm building I chose the second option, and to avoid bloating the code, I built a custom hook with working type suggestions/autocomplete. Hopefully it's useful for someone.
Usage:
Implementation:
You can also use for fields that have derived calculated value but also allow editing the field to another custom value. For example, you could have a salary field, and a firstMonthProrated field, which would use the fromValue and some math to derive the target value.
e.g.:
Beta Was this translation helpful? Give feedback.
All reactions