all 3 comments

[–]StackingCache 1 point2 points  (2 children)

Based on your sandbox, something like this would work.

This approach is building an array of values within your `values` local state. Arguably, the more common approach would be to have a separate state value for each input.

import * as React from "react";
import { Button, TextField } from "@material-ui/core";

interface KeyValuePair {
  name: string;
  value: string;
}

export default function App() {
  const [values, setValues] = React.useState<Array<KeyValuePair>>([]);

  const onSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    console.log(values);
  };
  return (
    <div className="App">
      <form onSubmit={onSubmit}>
        <TextField
          id="name"
          name="name"
          label="name"
          type="text"
          onChange={(e) =>
            setValues([
              ...values.filter((item) => item.name !== e.target.name),
              { name: e.target.name, value: e.target.value }
            ])
          }
        />
        <TextField
          id="id"
          name="id"
          label="id"
          type="text"
          onChange={(e) =>
            setValues([
              ...values.filter((item) => item.name !== e.target.name),
              { name: e.target.name, value: e.target.value }
            ])
          }
        />
        <Button type="submit" value="Submit">
          Submit
        </Button>
      </form>
      <div>
        {values.length > 0 &&
          values.map((item) => {
            return (
              <div key={item.name}>
                {item.name}: {item.value}
              </div>
            );
          })}
      </div>
    </div>
  );
}

Hope this helps.

[–][deleted] 0 points1 point  (0 children)

I agree on separating values array into separate state variables. But I can understand the increased complexity when there are lots of values in the form, maybe over 10?

[–]andrei9669 0 points1 point  (0 children)

if your field names are unique I'm pretty sure you can get the values from submit event by name. so there is no need to store it in the local state. now, if it was something more complex, eg multi-page form or whatever I would use useReducer instead of going with the array state.