Ga Yeon Kim
Ga Yeon Kim

Reputation: 101

How to set array in useForm and validate the length of value?

I'm using react-hook-form.
What I wanna do is to push a value to an array and validate the length of value.
This is defaultValue.

    defaultValues: {
      title: '',
      role: '',
      language: {source: '', target: []},
      industry: '',
      due_at: '',
      content: '',
    },

and this is input field that handles language.target.

<Controller
    name="language.target"
    control={control}
    rules={{
    required: true,
    setValues: (v) => setValue([...getValues('language.target'), v.value]),
    validate: (value) => {
    return '';
     },
      }}
    render={({field: {onChange}}) => (
       <Select
           options={languageIndex}
           onChange={(value) => onChange(value.value)}
           value={languageIndex.filter(
           (item) => item.value === getValues('language.target')
              )}
           placeholder="Select"
           />
       )}
 />

I tried this way to push a value like below and they didn't work..

Upvotes: 2

Views: 12226

Answers (1)

Akram Djidel
Akram Djidel

Reputation: 1

  1. use useFormContext() not useForm() for getValues and setValue: import { useFormContext } from 'react-hook-form';
    const { getValues, reset, watch, control, setValue } = useFormContext()

2)Now you can use append from useFieldArray and display the default values :

const { fields, append, prepend, remove, swap, move, insert, replace } = useFieldArray({
    control,
    name: `creation`,
  });
append({
      title: '',
      role: '',
      language: {source: '', target: []},
      industry: '',
      due_at: '',
      content: '',
    })

finaly, you can just name for controler , it changed automatiqualy :

<Controller
    name={`creation[${index}].language`}
    control={control}
   ......
 />

Upvotes: 0

Related Questions