【问题标题】:useFormContext inside FormProvider is nulluseFormContext inside FormProvider is null
【发布时间】:2022-11-09 12:35:00
【问题描述】:

I'm using react-hook-form to handle forms and I encountered an error that only happens on iOS (works fine on android) which tell me that useFormContext is null. The code contains three components so I wrote example on expo which you can find here, as you can see I'm using FormProvider so context should be sent to the children. Anyone has any ideas how to solve it?

Cannot read properties of null (reading 'control')
TypeError: Cannot read properties of null (reading 'control')
    at FormSelect 
<FormProvider {...methods}>
          <Dialog
            title={'issue-card'}
            body={
              <FormSelect
                name="card"
                label={'card-number'}
                options={cards}
              />
            }
            ...
          />
        </FormProvider>
export const FormSelect = ({
  label,
  options,
  name,
}) => {
  const { control } = useFormContext();
  const {
    field: { value, onChange },
    fieldState: { error },
  } = useController({ name, control });

  return (
    <FormControl>
        <Select
          onValueChange={onChange}
          selectedValue={value}
          variant="filled"
          _selectedItem={{ background: 'primary.black' }}
        >
          {options.map((option) => (
            <Select.Item
              key={`temporary--${value}`}
              label={option.number}
              value={option.number}
            />
          ))}
        </Select>
    </FormControl>
  );
};

    标签: react-native expo react-hook-form


    【解决方案1】:

    I'm adding my answer here because this is exactly the problem I just encountered and it might help someone else. For us it turns out the issue was incompatibility between versions of react-hook-form:

    1. We had developed some components in a reusable package that used react-hook-form@7.36.0
    2. We we were trying to use those components (via an NPM package) in a consuming project that was using react-hook-form@7.39.0.

    Aligning the versions of react-hook-form made the problem go away for us.


    In your particular case though, it looks like it's because of the way the Dialog control is rendering its children; if you move the FormProvider inside the body, then the control renders as you would expect:

    <Dialog
      title={'issue-card'}
      body={
        <FormProvider {...methods}>
          <FormSelect
            name="card"
            label={'card-number'}
            options={cards}
          />
        </FormProvider>
      }
    />
    
      猜你喜欢
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      相关资源
      最近更新 更多