Ben
Ben

Reputation: 93

Set defaultValues to Controllers in useFieldArray

Misunderstanding react-hook-forms.

I have a form for editing some stuff. Form contains fieldArray. I set initial formData in useForm hook using default values

const methods = useForm({ defaultValues: defaultValues });

where defaultValues is

const defaultValues = {
  test: [
    {
      name: "useFieldArray1"
    },
    {
      name: "useFieldArray2"
    }
  ]
};

And fieldArray. Here I'm using Controller (it's simplified case - in fact Custom input Controller more complex)

 <ul>
    {fields.map((item, index) => {
          return (
            <li key={item.id}>
              <Controller 
                    name={`test[${index}].name`}
                    control={control}
                    render={({value, onChange}) => 
                    <input onChange={onChange} defaultValue={value} />}
              />
              <button type="button" onClick={() => remove(index)}>
                Delete
              </button>
            </li>
          );
        })}
</ul>

When form is rendered everything is fine. Default values are displayed in input fields. But when I delete all fields and click append - new fields are not empty ... Default values are displayed again. And it happens only with Controller. Why it happens ? And how I can avoid it?

Please, here is CodeSandBox link. Delete inputs and press append to reproduce what I am saying.

https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-7mzyw?file=/src/fieldArray.js

Thanks

Upvotes: 4

Views: 7049

Answers (1)

Abhishek K
Abhishek K

Reputation: 51

<Controller
            name={name}
            rules={rules}
            defaultValue={defaultValue ? defaultValue : ''}
            render={({ field, fieldState }) => {
                return (
                    <TextField
                        inputRef={field.ref}
                        {...props}
                        {...field}
                        label={label}
                        value={field.value ? field.value : ''}
                        onChange={(event) => {
                            field.onChange(event.target.value);
                            props.onChange && props.onChange(event);
                        }}
                        style={props.style || { width: '100%' }}
                        helperText={fieldState?.error && fieldState?.error?.message}
                        error={Boolean(fieldState?.error)}
                        size={props.size || 'small'}
                        variant={props.variant || 'outlined'}
                        fullWidth={props.fullWidth || true}
                    />
                );
            }}
        />

Upvotes: 1

Related Questions