Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Created May 14, 2022 16:28
Show Gist options
  • Select an option

  • Save peteristhegreat/1ac98e80ce36b973e4a897e477d0440a to your computer and use it in GitHub Desktop.

Select an option

Save peteristhegreat/1ac98e80ce36b973e4a897e477d0440a to your computer and use it in GitHub Desktop.
Unhandled Runtime Error TypeError: field is undefined, typescript, react-hook-form, register

Symptom

Stacktrace

Unhandled Runtime Error

TypeError: field is undefined
Call Stack
ref
node_modules\react-hook-form\dist\index.esm.mjs (1799:0)
commitAttachRef
node_modules\react-dom\cjs\react-dom.development.js (20875:0)
commitLayoutEffects
node_modules\react-dom\cjs\react-dom.development.js (23431:0)
callCallback
node_modules\react-dom\cjs\react-dom.development.js (3945:0)

Issue

Mine was caused by an unallowed form in register. It accepts a lot of kinds of input, but it is tighter for typescript requiring the form: a.b.c and not a[b].c.

Here is the quote from the documentation:

https://www.react-hook-form.com/api/useform/register/#rules

  • we are using dot syntax only for typescript usage consistency, so bracket [] will not work for array form value.

    register('test.0.firstName'); // ✅ register('test[0]firstName'); // ❌

One way to fix this is to take whatever variable that was going into your brackets and make it a dotable string. Here is a function that should do that for whatever string key you were using before.

Transformation

<input
  className="m-2"
  {...register(
    // `owners[${[val]}].isOwner`  // Before
    `owners.${camelCase(val)}.isOwner` // After
  )}
  type="checkbox"
/>


function camelCase(str) {
  return str
    .replace(/\s(.)/g, function (a) {
      return a.toUpperCase();
    })
    .replace(/\s/g, '')
    .replace(/[^a-zA-Z]/g, '')
    .replace(/^(.)/, function (b) {
      return b.toLowerCase();
    });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment