React Hook Form: How to Manage Multiple Field Arrays with Conditional Rendering
I'm getting frustrated with I'm converting an old project and I'm relatively new to this, so bear with me..... I'm working on a form using React Hook Form (v7) that includes multiple field arrays which are conditionally rendered based on user input. The scenario arises when I try to remove an item from one of the field arrays; the state does not seem to update correctly, leading to index errors when trying to access fields. Here's a simplified version of my code: ```javascript import { useForm, useFieldArray } from 'react-hook-form'; const MyForm = () => { const { control, register, handleSubmit } = useForm(); const { fields: firstArray, append: appendFirst, remove: removeFirst } = useFieldArray({ name: 'firstArray', control }); const { fields: secondArray, append: appendSecond, remove: removeSecond } = useFieldArray({ name: 'secondArray', control }); const onSubmit = (data) => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {firstArray.map((item, index) => ( <div key={item.id}> <input {...register(`firstArray.${index}.name`)} /> <button type="button" onClick={() => removeFirst(index)}>Remove</button> {item.showSecondArray && ( <div> {secondArray.map((subItem, subIndex) => ( <div key={subItem.id}> <input {...register(`secondArray.${subIndex}.description`)} /> <button type="button" onClick={() => removeSecond(subIndex)}>Remove</button> </div> ))} </div> )} </div> ))} <button type="button" onClick={() => appendFirst({ name: '', showSecondArray: false })}>Add First Array Item</button> <button type="submit">Submit</button> </form> ); }; ``` The question occurs when I remove an item from `firstArray` that has a second array displayed. The indices of the remaining items get messed up, especially for `secondArray`. I get the following behavior in the console when trying to access an index that no longer exists: `want to read property 'description' of undefined`. I've tried adding `key` props to the second array items, but that didn't resolve the scenario. How can I ensure that removing an item from one field array correctly updates the state of the other fields, especially when they are conditionally rendered? My development environment is macOS. I'd really appreciate any guidance on this. Could this be a known issue? I'm working on a microservice that needs to handle this. For context: I'm using Javascript on Ubuntu 20.04. Thanks for taking the time to read this!