final-form / react-final-form-arrays

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

Conditionally visible FieldArrays pushing to wrong field #156

Open karlshea opened 3 years ago

karlshea commented 3 years ago

Are you submitting a bug report or a feature request?

bug report (reopening #142)

What is the current behavior?

I have a FieldArray for an outer array, and then a conditionally-visible FieldArray for an inner array. Pushing to the outer field always pushes to the initially-visible index, whereas pushing to the inner field works correctly. (The working case is not shown in the sandbox, but the third-level arrays do work)

When inspecting the field array values in the debugger it all looks correct, it is pointing at the correct item. My guess is that it's something to do with useConstant currying the mutators. Maybe that hook needs to reinitialize when the passed field name changes?

In my project I was originally passing in fields that FieldArray gives to the render function down to the child component and using the push() function available there, and that also did not work.

What is the expected behavior?

push() should push the item into the correct array index.

Sandbox Link

https://codesandbox.io/s/elastic-kapitsa-qw0ku

Directions

  1. Click "Push with useFieldArray". New item is added to OuterValues[0].NestedValues.
  2. Click "Push with form mutator". New item is added to OuterValues[0].NestedValues.
  3. Change index from 0 to 1 using select at top of form.
  4. Click "Push with useFieldArray". New item incorrectly added to OuterValues[0].NestedValues.
  5. Click "Push with form mutator". New item correctly added to OuterValues[1].NestedValues.

What's your environment?

React 17, latest everything else.

Workaround for others

Don't use push() exposed by FieldArray's fields for this use-case. Instead, use form.mutators.push and pass in the full field name e.g. push('OuterValues[1].NestedValues', { ... }).

tjb042 commented 3 years ago

Similar problem, same fix. Working with nested arrays where the inner array is conditional or may be a different shape than its parent seems to cause some of the mutator functions passed through FieldArrayRenderProps to act up. However calling the form's mutator functions directly seems to work fine. Note that the name prop from FieldArrayRenderProps is correct for the field it should be rendering.

VasiliKubarka commented 3 years ago

@erikras I think this bug is critical for work with useFieldArray and because of this reason useFieldArray could be deprecated in our project. Do you have any plans to fix it?

pavsmk commented 3 years ago

I have the same issue like on the @karlshea's sandbox example. Only form.mutators or from.change help me