Skip to content

Provide descriptive error msgs for illegal use of Morfi hooks  #22

Description

@abdulhadi-lababidi98

I was building new form called ProductDefinitionMigrateForm, and inside this form I needed to change specific field value (called productVersion) and I did this:

export const ProductDefinitionMigrateForm: React.FC = () => {
    const { buttonRef, onSubmitFailed } = useFormErrorHandling();
    const [data, setData] = useState(() => Morfi.initialData(_formInitialData()));
    const { Form, fields } = Morfi.useForm<ProductDefinitionMigrateFormData>();
    DirtyGuard.useForm(data);


    const PVField = Morfi.useField(fields.productVersion);


This caused the app to crash and the following error was in the console:
Uncaught TypeError: Cannot destructure property 'update' of '(0 , import_react.useContext)(...)' as it is null.

After a while of debugging I realised that I can't use the useField hook here because it injects data provided from useForm hook through the context.

Expected behaviour

We should add a clear error message that tells the developer exactly what went wrong, so they don't have to dig into the library to figure out the reason.

Suggested solution

Update the useField hook to add this validation

const useField = (field) => {
  const context = useContext(morfiContext);
  if(context === null) throw new Error('[IlligalUseError]: Form not found, please make sure that one of the ancesstors of the hook caller is a form element')
  const { update, getData, isRequired } = context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions