willowtreeapps / react-formable

React Forms
25 stars 5 forks source link

Add the ability to map over values #9

Open kaw2k opened 8 years ago

kaw2k commented 8 years ago

Thinking ahead to more use cases, transforming data is quite a common form function. With normal forms this is easy, you just map over your data in onSubmit. When you start having reusable components such as complex inputs or reusable Fieldsets / Fieldlists, we may want to encapsulate the transformation logic within those components.

Throwing this out there for now, but we may want to add a map prop to any object within a form. This would behave almost identically to how validators works. Anything can have them, whatever they return is the new value.

This seriously complicates the serialization logic as we lean on a predictable form structure to mirror the fieldValues and fieldErrors. With that in mind I am hesitant to implement this without a solid need.

kaw2k commented 8 years ago

With an upcoming refactor to how we serialize the form, this is now quite easy to accomplish. The question is do we even want it? In my mind, there are a few use cases:

Reusable components

Let's say we make a Person Fieldset that is common throughout our application. It contains a first name and last name but we want the full name as well (a computed property!)

function mapPersonFieldset(fieldValues) {
    return {
        ...fieldValues,
        fullName: `${fieldValues.firstName}  ${fieldValues.lastName}`
    }
}

function personFieldset() {
    return <Fieldset name="person" map={mapPersonFieldset}>
        <Input name="firstName" />
        <Input name="lastName" />
    </Fieldset>
}

The map property accepts a function which receives the fieldValue for the field. For inputs it is a primitive, Fieldset and Form get objects, and Fieldlist get arrays.

Problems

The question is, when does map get called? My gut says after validation happens. Mapping over our data makes it so our fieldErrors and fieldValues params are no longer in tandem, but I don't think this is an issue anymore with the <Errors /> component.

uttrasey commented 8 years ago

I think this issue of somewhat linked with https://github.com/willowtreeapps/react-formable/issues/47.

It would be interesting to see how we can model the data + errors at various component and sudo component levels. Sudo component being like a wrapper thingy.

kaw2k commented 8 years ago

This is referenced from #77