Search code examples
reactjsreact-hooksreact-contextreact-hook-formreact-admin

useFormContext() is null but its context state exist. How can I get it?


Currently react-admin: ^4.8.3 / react-hook-form: 7.40.0.

I have the following code:

import { useFormContext } from 'react-hook-form'

const MyComponent = () => 
{
  const {formState: {isValid}} = useFormContext()
  // provoke a crash as useFormContext() is null
  return <></>
}
import {
  SimpleForm,
  TextInput,
  maxLength,
  required,
} from 'react-admin'

const FooForm = () => {
  return (
    <SimpleForm
      mode="all"
      reValidateMode="onChange"
      toolbar={toolbar}
      onSubmit={save}
    >
      <TextInput
        label="resources.resourceName.fields.name"
        source="name"
        validate={[required(), maxLength(50), noEmptySpace]}
      />
      <MyComponent/>
    </SimpleForm>
  )
}

useFormContext() = null and its deconstruction provoke a crash.

Using React Context Devtool I know that the context exist with the name debugId_${randomNumber} with the right updated values and the form state like isValid.

form context using React Context Devtool

How can I fix useFormContext() being null or access this unnamed react context by another way ?

I tried to use useFormState but it require field control that I cannot have access, or it is from a useless empty new useForm().

I also tried to use useContext(FormGroupsContext) but it only has functions to register fields and does not have state or context names.

For those who are asking, react-admin SimpleForm use react-admin Form which use FormProvider that should pass its context to children. I should not have useFormContext() = null.

How can I fix useFormContext() being null or access this unnamed react context by another way ?


Solution

  • My code was right from the beginning, the issue was that since my project was old, I had an old webpack with lots of babel and config override that completly broke this exact context. I migrate my project to use vitejs and everything is fine now !