I'm trying to set a variable "list" in an "if" statement, and after that, update my data via useState, but if I write setData outside the "if" statement, it shows that the variable "list" is not defined, so I must rewrite all the code inside the "if" and the "else" statement (which is not desirable)
const [data, setData] = useState({
name: "",
email: "",
machinetype: [],
});
const handleInputChange = (event) => {
if (event.target.name === "machinetype") {
const chck = event.target.checked;
if (chck) {
const list = data[event.target.name].concat([event.target.value]);
} else {
const index = data[event.target.name].indexOf(event.target.value);
const remove = data[event.target.name].splice(index, 1);
const list = data[event.target.name];
}
setData({
...data,
[event.target.name]: list,
});
}
};
Any advices? Thanks
Aucun commentaire:
Enregistrer un commentaire