I'm writing a form in ReasonReact. I used reducerComponent
and a record as state. Let's say I have something like this:
type state = {
field1: string,
field2: int,
};
type action =
| SetField1(string)
| SetField2(int);
let component = ReasonReact.reducerComponent("SomeComponent");
let make = ( _children) => {
...component,
initialState: () => {field1: "", field2: 0},
reducer: (action, state) => switch(action) {
| SetField1(value) => ReasonReact.Update({...state, field1: value})
| SetField2(value) => ReasonReact.Update({...state, field2: value})
},
render: ({state, send}) =>
<div>
<input value={state.field1} onChange={e => send(SetField1(getValue(e)))} />
<input value={state.field2 |> string_of_int} onChange={e => send(SetField2(e |> getValue |> int_of_string))} />
</div>,
}
In this example there are only 2 fields, but how to handle if there are for example 30 fields? Does that mean that I have to create 30 different actions and handle this 30 times in reducer? It's a lot of insignificant code. It there any way to modify the record more dynamically, or maybe i should use another structure for state (object, Js.t)?
To clarify i use this kind of forms in two cases:
- To convert state to Js.Json.t (using bs-json) and send to server (using bs-fetch)
- To send it to server using reason-apollo (graphql) as a mutation.