I have an onChange handler with which I can edit certain objects with input fields.
The onChange handler looks like this:
// First I get the current state
const [persons, setPersons] = useState(service.persons);
The API returns the following for persons (an array of objects):
contacts (2) [{…}, {…}]
0: {person_company: "Google", person_name: "John Doe"}
1: {person_company: "Facebook", person_name: "Jane Doe"}
My onChange handler looks like this (..first part of the if statement for editing the given persons works perfectly, but the else statement for creating a new person doesn't):
const updatePersons = (e: any, index?: number) => {
if (index !== undefined) {
const updatedPersons = [...persons];
updatedPersons[index][e.target.name] = e.target.value;
setPersons(updatedPersons);
} else {
setPersons({ ...persons, [e.target.name]: e.target.value });
}
};
My template looks like this (just empty input fields for creating a new person with a person_company and person_name):
<InputContainer>
<p>New person</p>
<InputWrapper>
<TextField
type="text"
label="Person company"
name='person_company'
value=' '
onChange={e => updatePersons(e)}
/>
</InputWrapper>
<InputWrapper>
<TextField
type="text"
label="Person name"
name="person_name"
value=' '
onChange={e => updatePersons(e)}
/>
</InputWrapper>
</InputContainer>
Unfortunately, it doesn't work that way.
Only the first letter is realized in the first input field and the whole component disappears afterwards
If I manipulate it so that the component does not disappear, the value of the input field is not updated (this is probably because I set value = ' '. I have no idea what else I should provide).
If I console log persons after the first letter as mentioned in 1., the array of object is updated as follows:
contacts {0: {…}, 1: {…}, company_name: " t"} 0: {person_company: "Google", person_name: "John Doe"} 1: {person_company: "Facebook", person_name: "Jane Doe"} person_company: " t"
But my goal is that the object should be updated as follows when I create a new person:
contacts (3) [{…}, {…}, {…}]
0: {person_company: "Google", person_name: "John Doe"}
1: {person_company: "Facebook", person_name: "Jane Doe"}
2: {person_company: "Amazon", person_name: "Max Mustermann"}
What am I doing wrong here?