'Input from a textfield autofills the other textfields based on data

I have this example data:

export const data = [
  {
    state: "state",
    firstName: "Alex",
    lastName: "Dhan",
    country: "US"
  },
  {
    state: "state2",
    firstName: "Pin",
    lastName: "Io",
    country: "Japan"
  },
  {
    state: "state3",
    firstName: "Third",
    lastName: "last name3",
    country: "South Korea"
  },
  {
    state: "state4",
    firstName: "Alex",
    lastName: "Kin",
    country: "South Korea"
  },
  {
    state: "state5",
    firstName: "Alex",
    lastName: "Kin",
    country: "India"
  }
];

How can I match the first and last name that was entered by the user, and then have it autofill the other textfields as well? There might also be instances where first names are the same or the first and last name are the same but the state and country is different. How can I do this?

Recreated codesandbox: https://codesandbox.io/s/textfield-with-search-f2fjx1?file=/data.js:0-513

 <form onSubmit={handleSubmit}>
      <TextField
        variant="outlined"
        label="First Name"
        fullWidth
        value={firstName}
        onChange={(e) => setFirstName(e.target.value)}
        required
      />
      <TextField
        variant="outlined"
        label="Last Name"
        fullWidth
        value={lastName}
        onChange={(e) => setLastName(e.target.value)}
        required
      />
      <TextField
        variant="outlined"
        label="State"
        fullWidth
        value={state}
        onChange={(e) => setState(e.target.value)}
        required
      />
      <br /> <br />
      <button type="submit">Submit</button>
      <br />
    </form>


Solution 1:[1]

use useEffect. there do all the necessary checks. or all the same checks in submit

useEffect(() => {
  const res = Object.values(data).filter(item => {
    /* check for matches here */
    return item.firstName === firstName && item.lastName === lastName
  });
  if(res.length === 1 && !state) {
    /* fill in the required fields here */
    setState(res[0].state)
  }
  /** here you specify the necessary dependencies (which will be in the filter) */
}, [firstName, lastName]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Юрий Копоть