1

There is something that I am blocking and it makes no sense at all. For you who are familiar with react-hook-form, I am attempting to create a dynamic field array that renders according to the state object. The thing is, it renders on the first render but not on the second render.

Example:


    let subK = [{ name: '' }]
    if (kategories[kategori] !== undefined) {
        //subK = kategories[kategori].subKategori.map(x => ({ name: JSON.stringify(x) }))
        subK = kategories[kategori].subKategori.map(x => ({ name: (x) }))
    }
    console.log(subK) // it logs[{name: 'kat1'},{name: 'kat2'}]

    //defines the form
    const { register, control, handleSubmit } = useForm({
        defaultValues: {
            subKategori: subK
        }
    });

does not render subK.

But if I do

    let subK = [{ name: '' }]
    if (kategories[kategori] !== undefined) {
        //subK = kategories[kategori].subKategori.map(x => ({ name: JSON.stringify(x) }))
        subK = kategories[kategori].subKategori.map(x => ({ name: (x) }))
    }
    console.log(subK)

    //defines the form
    const { register, control, handleSubmit } = useForm({
        defaultValues: {
            subKategori: [{name: 'kat1'},{name: 'kat2'}]
        }
    });

it renders as it is supposed too.

What am I doing wrong?

8
  • Can you provide a codesandbox for reproducing the issue? Commented Mar 25, 2020 at 13:25
  • @NiyasNazar not really. The project is quite big and for a client. Don't want it to leak over the internet and the code blocks that I provided are the core of react-hook-form and useFieldArray() Commented Mar 25, 2020 at 13:30
  • Where does kategories come from ? Commented Mar 25, 2020 at 13:35
  • @nubinub from the state. Commented Mar 25, 2020 at 13:35
  • 2
    As suggested by @NiyasNazar, you should really narrow down and abstract the problem you are facing. First of all it might help you solve the problem, and second of all it will allow you to post a sandbox. Commented Mar 25, 2020 at 13:38

1 Answer 1

0

There is a minor issue in the structure of subKategori at line number 8. It seems an array is in stringified form. But for map, you need an array. Converting it as following at line number 8 shall work :

....
 kat1: {
          subKategori: ["kat1", "kat2"]
        },
...

Here is the updated sandbox link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.