Search code examples
reactjsreduxredux-form

Submitting additional field attributes using Redux Form


I have a redux-form driven form that's being constructed via JSON sent from my backend. This data has specific keys that I need to post back on submit (e.g. filterID). Redux-form appears to keep a fairly minimal state representation of the form/fields. As an example, here's a trivial state dump:

{form : {
    myForm: {
        registeredFields: {
            field1: {name: "field1", type: "Field", count: 1},
            field2: {name: "field2", type: "Field", count: 2}
        },
        values: {
            field1: "123"
        }
    }
}

Is there a built-in way using redux-form that I could have it store additional data in the state (e.g. filterID), or key off of a attribute/prop than name?

<Field
      key={somethingunique}
      name={component.name}
      component={component.type}
      filterID={component.id}
/>

This would yield something like the following state (move the additional stuff/filterID around anywhere as long as it's present):

{form : {
    myForm: {
        registeredFields: {
            field1: {name: "field1", type: "Field", count: 1},
            field2: {name: "field2", type: "Field", count: 2}
        },
        values: {
            field1: "123"
        },
        additionalStuff: {
            field1: {filterID: "abc"}
        },
    }
}

My thinking with this approach is that it's easily grabbed in handleSubmit such that I can send it back to the server with a simple stringify.

I can play some games with adding a big object to state and doing lookups on submission, connecting components, etc., but those feel messy.


Solution

  • As of now I don't see a way to solve this with redux-form alone. Instead, when a new form definition comes across, I add it to the global state with a basic action/reducer. In my form's handleSubmit function, I derive a new submission object from the one that redux form constructs by using the name fields as keys in the state form definition. This allows me to easily lookup whatever values are necessary for the backend and submit my new derived object.