Home > Software engineering >  react-hook-form, error when using for data update
react-hook-form, error when using for data update

Time:11-08

I am trying to configure a react-hook-form to work for create and update operations. I am using material ui autocomplete and textfield. The problem I am facing is with a field that has autocomplete.

If I pass an input value, it displays it, but when the form is submitted, the required error is triggered (as if the field has not been filled in).

This is my code:

         <Controller
                control={control}
                name="type"
                render={({ field: { onChange, value }, fieldState: { error } }) => (
                  <Autocomplete
                    value={value}
                    onChange={(event, item) => {
                      onChange(item.value);
                  }}
                    id="type"
                    defaultValue={props.operation === 'edit' ? props.values.type : null}
                    options={projectTypes}
                    renderInput={(params) => <TextField {...params}
                      error={!!error}
                      helperText={error ? error.message : null}
                      label="type"
                      {...register('type')}
                    />}
                  />
                )}
             
                rules={{ required: 'Project type is required' }}
              />

enter image description here

I have tried to add the input value as "inputValue", but then my options, are not available and I cannot either clear the value from the field.

Any ideas on what is wrong here?

CodePudding user response:

The problem is you're using both <Controller /> and register to register your field.

You should only use one of them, in your use case you should use <Controller /> and get rid of the register call inside your <TextField />.

You should also pass the defaultValue for your field to <Controller /> instead of passing it to <Autocomplete />.

<Controller
    control={control}
    name="type"
    defaultValue={props.operation === 'edit' ? props.values.type : null}
    render={({ field: { onChange, value }, fieldState: { error } }) => (
        <Autocomplete
            value={value}
            onChange={(event, item) => {
                onChange(item.value);
            }}
            id="type"
            options={projectTypes}
            renderInput={(params) => (
                <TextField
                    {...params}
                    error={!!error}
                    helperText={error ? error.message : null}
                    label="type"
                />
            )}
        />
    )}
    rules={{ required: 'Project type is required' }}
/>
  • Related