I am trying to update an array of object which contain my checkbox data. I need to update the value field when user clicks the checkbox. I think I can achieve this by using a mapping through the array and then using the spread operator to update the state.
My doubt is why the state is updating when using a find method? I thought only set method can update the state. Sorry in advance if this is an obvious noobie mistake.
let checkBoxDataTemp = [
{
name: "spam",
value: false,
},
{
name: "dangerousProduct",
value: false,
},
{
name: "sexuallyExplicit",
value: false,
},
{
name: "other",
value: false,
},
];
const [checkBoxData, setCheckBoxData] = useState(checkBoxDataTemp);
const changeInput = (input) => {
const { name, value } = input;
// Why is the below code updating the state eventhough I am not using setCheckBoxData
checkBoxData.find((item) => item.name === name).value = value;
};
please check the changeInput function.
EDIT: How to approach incase of data that should remain unchanged?
let checkBoxDataTemp = [
{
name: "spam",
label: "Spam",
value: false,
},
{
name: "dangerousProduct",
label: "Dangerous products",
value: false,
},
{
name: "sexuallyExplicit",
label: "Sexually explicit"
value: false,
},
{
name: "other",
label: "Other",
value: false,
},
];