react-hook-form: Rules of Controller does not react to changes
First, the lib is very cool!! Thanks!
My problem is in set the rule in Controller:
{{ required: needRegister, min: 3 }}
The property rules of Controller does not not react to needRegister
Codesandbox link (Required)
- Controller Template
Expected behavior React to changes in rules
Desktop (please complete the following information):
- OS: Arch Linux Amd64
- Browser Firefox
- Version 77
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 36 (24 by maintainers)
@bluebill1049 Controlled Input and Uncntrolled Input are inconsistent. Shouldn’t this be fixed?
https://codesandbox.io/s/react-hook-form-controller-template-oolpt
if anyone’s situation is simply depend on a prop, and it change only once, maybe use
keyprop to forceControllerrecreate the component helpsThanks for your feedback. have a read on the note above first to understand the rationale behind: https://github.com/react-hook-form/react-hook-form/issues/1749#issuecomment-637248515
Because rules are cached, so once it’s
unregistred, it will getregisteredat the render with updatedrules.if it’s coming down as props, then same use case with
unregister, if it’s trigger by user input, you can usevalidateandgetValues.Sorry deleted previous message…
I think i found an easier solution: you can update the rules by invoking
registeragain.https://codesandbox.io/s/controller-rules-8pd7z?file=/src/App.tsx
let me know if this helps.
Summarise
We have the following options:
registeron each render without cache rulesrulesrules3 ✅(what we choose at the moment, cheap and have work-around)
yea, hopefully not going to introduce too much code for this change. I did have a note on the documentation on this too that we cache the rules.
We do have
compareObjectmethod, but then you will need deep compare with validating function which is not going to be pretty and light weight compare.This? Okay, thanks @bluebill1049 ! I have the luxury of waiting for the release, so I’ll do that for now!
@acfasj we are fixing this next release.
ok, I will take a look closer during lunch time.
Thanks 😄
I think we should take this as a tradeoff and documented the solution and attach that under the rules section.
unregister.validatefunction withgetValues()to read other inputs’ value .🤔 an alternative solution will be on users to memo all the rules, which is not great DX.
You’re right. This may not be light weight compare.
we cache the rules object inside the controller, hence the validation rules is not changing. (so the user doesn’t have to memo the rules object themself)
Solutions
validatefunction combinedgetValues()(assume the toggle input is register with hook form as well)unregisterthat input, so input gets re-registered with updatedrules.