final-form / react-final-form-arrays

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

Field Value Keys are dropped if field is empty #178

Open creativeindustriesgroup opened 1 year ago

creativeindustriesgroup commented 1 year ago

The current behaviour?

If a field is emptied by the user after typing into it, the key:value pair is automatically removed from the values array. e.g. in the following code:

<FieldArray name="customers">
              {({ fields }) =>
                fields.map((name, index) => (
                  <div key={name}>
                    <label>Cust. #{index + 1}</label>
                    <Field
                      name={`${name}.firstName`}
                      component="input"
                      placeholder="First Name"
                    />
                  </div>
                ))
              }
            </FieldArray>

Returns the following values when "My Name" is typed into the field: { "customers": [ { "firstName": "My Name" } ] }

But when the firstName field is emptied, the customers[0].firstName key and value is removed from the object, although the object still remains present: { "customers": [ {} ] }

What is the expected behaviour?

React-Final-Form accepts an allowNull prop. The default behaviour intending to prevent null values to ensure controlled inputs. Fields inside an array should follow this behaviour.

This, however, isn't an issue relating to controlled inputs. I dynamically render my form inputs based on an array of fields sent to initialValues and removing the key/pair from the values object removes the field from the form the key no longer exists.

The suggestion If the field is emptied and you are left with an empty value, the values object returns: { "customers": [ { "firstName": "" } ] }

Perhaps if allowNull is true, the entire key/value pair is removed from the object

What's your environment?

This is re-creatable in the Basic Example

Other information

NB: If anyone has any alternate suggestions to get around this then I'd be happy to hear them!