You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a component to display the error message of a named field. I used to do it this way:
import{useFormContext,typeFieldError,get}from'react-hook-form';exportdefaultfunctionFormError({ name } : {name: string}): ReactElement{// Get the label from our own field contextconst{ label }=useFieldContext();// Get the errors from the form context stateconst{formState: { errors },}=useFormContext();// Get our specific error based on the name via the `get` functionconsterror=get(errors,name)asFieldError|undefined;// Get the error message to render, if we have an errorconstmessage=error==null
? null
: isNotEmpty(error.message)
? `"${label}" ${error.message}`
: error.type;// Then render the message, if we have any, with aria-live and all that jazz ...}
I have now tried to enable the React Compiler on our project, and it seems that this no longer works, probably because the formState and/or errors objects are stable and therefore gets memoized by the compiler.
So, I need an alternative way to get this error, and the simplest way I could think of was to instead do this via useController:
// Insead of errors, get the control from the form contextconst{ control }=useFormContext();// Use useController to get our errorconsterror=useController({ control, name }).field.error;// Continue as before ...}
Is this a safe/ok/good way to do it? Particularly, is it a problem to use useController in multiple components with the same name?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
I have a component to display the error message of a named field. I used to do it this way:
I have now tried to enable the React Compiler on our project, and it seems that this no longer works, probably because the
formState
and/orerrors
objects are stable and therefore gets memoized by the compiler.So, I need an alternative way to get this error, and the simplest way I could think of was to instead do this via
useController
:Is this a safe/ok/good way to do it? Particularly, is it a problem to use
useController
in multiple components with the samename
?Beta Was this translation helpful? Give feedback.
All reactions