1
hi everyone, i got an issue im stuck at.

i got a nested object, (for the sake of simplicity, i've updated the object to be much less complicated) here is what it looks like:

export const customerDraft = {
  _id: "6368dab51482da28ba792712",
  firstName: "Jane",
  lastName: "Doe",
  metadata: {
    birthDate: "25.07.1999",
    gender: "Female",
    status: "Adult",
  },
};

the problem to be solved is as follows:

  • i have to display all the keys of the object as inputs so the user can update it. (which was fairly easy, i did it using recursion) here is what it looks like:
const Inputs = ({ data }) => {
  // const [updatedCustomerDraft, setUpdatedCustomerDraft] = useState({});

  return (
    <form style={{ display: "flex", flexWrap: "wrap", gap: "2em" }}>
      {Object.keys(data).map((key, i) => {
        if (data[key] !== null && typeof data[key] === "object") {
          return <Inputs key={i} data={data[key]} />;
        }
        return (
          <FormControl key={i}>
            <InputLabel>{key}</InputLabel>
            <Input
              defaultValue={data[key]}
              onInput={(e) => {
                const { value } = e.target;

                handleChange(key, value, data);
              }}
            />
          </FormControl>
        );
      })}
    </form>
  );
};

and also the picture: enter image description here

Now the tricky part:

  • whenever user types something in that input, the object should be dynamically updated, for example if user types 'Ann', in firstName, firstname value should be equal to 'Ann'. and if the user types for example 'non-binary' in gender key, its value should also be updated.

i want to create deep copy of the initial object, update it and then return the updated object. this is currently where i'm at:

const handleChange = (key, value, data) => {
  if (key in data) {
    data = { ...data, [key]: value };

    console.log(data);
  } else {
    handleChange(key, value, data[key]);
  }
};

Any feedback at all with a good explanation would be much appreciated!!

thanks!

ikkako
  • 29
  • 9

0 Answers0