kaliberjs / forms

Forms for React
MIT License
4 stars 0 forks source link

Duplicate field names when using `useArrayFormField` #6

Closed peeke closed 4 years ago

peeke commented 4 years ago

Removing an array item through the helper method returned by useArrayFormField can lead to duplicate field names.

This happens when:

  1. You have 2 array form field children
  2. You remove the first one
  3. You add another one

Both child fields will now have the name form1.arrayfield[1]

EECOLOR commented 4 years ago

Great find! Weird I didn't spot it myself.

Question is: how to solve? I think we have a few approaches:

  1. Use a separate counter that counts towards infinity. Here the last added field has the highest number. Problem with this approach is that the name will contain gaps.
  2. Provide new names for all fields so that they remain ok. This means we would need a drastic change to the API as name would need to become part of the state.
  3. Reuse indexes by recording deleted fields. This could become weird as later fields would have a lower index in the name.

  1. I think I like this option most. Added complexity is minimal. API remains the same.
  2. This is for the purists. I don't think the benefits outweigh the complexity cost (implementation and API).
  3. Not good, added complexity for no benefit.

I would go for 1. In the rare case that we actually need the name to be correct (which I don't think we will encounter) because we use an old school backend we have a few escape hatches:

I think we should only consider a complex alternative once we have a use case.

@peeke What do you think?

peeke commented 4 years ago

Based on the above, I'd prefer option 1 as well.