react-hook-form: When registering a field manually, defaultValues no longer prefill

Describe the bug Starting with react-hook-form version 3.24.2-beta.2, when registering a field manually (instead of inside a ref), defaultValues are no longer filled.

To Reproduce

  1. Using the codesandbox below, in package.json change the react-hook-form version from 3.24.2-beta.1 to 3.24.2-beta.2.
  2. Note that the default value of “josh” is no longer prefilled

Codesandbox link https://codesandbox.io/s/react-hook-form-defaultvalues-t8js7

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 19 (17 by maintainers)

Most upvoted comments

Nice one @barrymay.

Not defining name there was a mistake when transferring to the codesandbox, but removing name from the passed options does work. Thanks!

And thanks @bluebill1049 for being so on top of things!

thx - btw, the reason the old code didn’t have this issue was because we just ignored whatever was there as name in the second param - now we do care about it.

Hi @jsteiner - upon reviewing this, I’m going to state this is not a bug but a improved clarity in implementation.

Your code in your sandbox is this

      register(someRef.current, {
        name,
      })

but what that’s doing is setting a new name property in the second param to an unwanted variable, since name is never defined as a variable elsewhere in that code (that’s what the code sandbox redline is complaining about).

(What’s worse in this specific scenario is that name is NOT undefined, it’s actually setting to window.name, which is a typeof string, which is causing more confusion). If you set name: undefined there, the code actually runs with the default.

In the newer versions of react-hook-form, in order to support scenarios like react-native, we’re allowing the name object property to be specified there and using it. If you’re not using that, then you should leave that name prop undefined/unset and the process will work as you want

Therefore, In your case you should just say:

      register(someRef.current)

which was better in the first place IMO 😃

Therefore I’m not going to make a change here, I believe this is working as we want it to. If you had another idea about this let me know.

that said, the workaround you mentioned @bluebill1049 should definitely but it’s potentially a bit ugly to read…

‘boo’ on me 😃 I’ll make a fix tonight and will add a test to match 😃