If I have the following object in state. What is the correct way to write a setState function to update formList[1].name from "Name2" to "New Name"? Each of these fields are linked to an input field.
state = {
formList = {
0 : {
id: 10,
name: "Name1",
date: "11/27/2019"
},
1 : {
id: 11,
name: "Name2",
date: "11/27/2019"
}
}
}
I tried the below. Where for my example above, index is passed 1 and field is passed "name". I would like to keep the field name dynamic so that I could use this for all input fields
METHOD 1
updateForm = (e, index, field) => {
const newValue = e.target.value;
this.setState((prevState) => {
return {
edittedDataList: {
...prevState.edittedDataList,
[prevState.edittedDataList[index][field]]: newValue
}
}
})
}
But whenever I start typing into the name input field, my state changes to the below
RESULT 1
state = {
formList = {
0 : {
id: 10,
name: "Name1",
date: "11/27/2019"
},
1 : {
id: 11,
name: "Name2",
date: "11/27/2019"
},
Name2: "Name21" // where 1 is the character I pressed
}
}
I also tried setting state using the below. It actually works with setting the state but I believe it may mutate the state so I don't think it is the correct way to setState. It also has a weird side effect
METHOD 2
updateForm = (e, index, field) => {
const newValue = e.target.value;
this.setState((prevState) => {
return prevState.edittedDataList[editAtIndex][field] = newValue;
})
}
RESULT 2
state = {
0: "N",
1: "e",
2: "w",
3: " ",
4: "N",
5: "a",
6: "m",
7: "e",
formList = {
0 : {
id: 10,
name: "Name1",
date: "11/27/2019"
},
1 : {
id: 11,
name: "New Name",
date: "11/27/2019"
}
}
}
Can someone show me the correct way to write setState and explain why my current setState functions are having strange results?
Thanks in advance
Try
updateForm = (e, index, field) => {
const { edittedDataList } = this.state;
edittedDataList[index][field] = e.target.value;
this.setState({ edittedDataList });
}