final-form / react-final-form-arrays

A component for rendering and editing arrays 🏁 React Final Form
MIT License
204 stars 69 forks source link

Infinite loop: useFieldArray with { initialvalue: [] } #111

Open Togrias opened 5 years ago

Togrias commented 5 years ago

Are you submitting a bug report or a feature request?

Bug Report

What is the current behavior?

Inside a <Form/>, try the following: useFieldArray('fieldName', { initialValue: [] }); The following error message should occur:

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.

There is a workaround. The error goes away if the initialValue is a constant or memoized value that doesn't update with each render. const emptyArray = []; useFieldArray('fieldName', { initialValue: emptyArray });

What is the expected behavior?

Since FieldArray deals primarily with arrays, I believe the desirable behaviour is to expect and handle arrays intuitively. Intuitively, passing a different array "container" on each render but with the same elements and order should not cause an infinite loop.

Sandbox Link

Please see the above for reproduction.

What's your environment?

final-form: 4.18.5 final-form-arrays: 3.0.1 react: 16.9.0 react-dom: 16.9.0 react-final-form: 6.3.0 react-final-form-arrays: 3.1.1

Other information

cyonder commented 4 years ago

+1

I have a form where users can add multiple questions and each question can have multiple answers. So every time user clicks on a button fields.push({ answer: '' }) fires and it adds a new input field to be populated with an answer.

However, I would like to display 2 or more answer input fields as soon as a question is added to form. Basically I do this initialValue={[{ answer: '' }, { answer: '' }]} This works! Although as soon as I add a field level validation to <FieldArray name={${name}.answers} initialValue={[{ answer: '' }, { answer: '' }]}> or its wrapper/parent <FieldArray name="questions"> I receive the error above.

I found a work around. Instead of using initialValue, I programatically populate the answers by doing fields.length < 1 && fields.push({ answer: ''})

chillyistkult commented 3 years ago

It is still an issue any update?