The function handleForm
is triggered when the button is clicked, and it is supose to check all the inputs.
const [errorMessage, setErrorMessage] = useState({
lastName: "",
firstName: "",
lastNameHiragana: "",
firstNameHiragana: "",
birthday: "",
sex: "",
telephone: "",
email: "",
joinedDate: "",
division: "",
});
const [values, setValues] = useState({
lastName: "",
firstName: "",
lastNameHiragana: "",
firstNameHiragana: "",
birthday: "",
sex: "",
telephone: "",
email: "",
joinedDate: "",
division: "",
});
function handleForm(e) {
e.preventDefault();
for (const name in values) {
const hiraganaRegex = /^[ぁ-ん]+$/;
switch (name) {
case "lastName":
if (!values[name]) {
setErrorMessage({ ...errorMessage, lastName: "必須項目です" });
}
break;
case "firstName":
if (!values[name]) {
setErrorMessage({ ...errorMessage, firstName: "必須項目です" });
} else {
setErrorMessage({ ...errorMessage, firstName: "" });
}
break;
case "lastNameHiragana":
if (!hiraganaRegex.test(values[name]) && values[name]) {
setErrorMessage({
...errorMessage,
lastNameHiragana: "ひらがなで入力して下さい。",
});
}
break;
case "firstNameHiragana":
if (!hiraganaRegex.test(values[name]) && values[name]) {
setErrorMessage({
...errorMessage,
firstNameHiragana: "ひらがなで入力して下さい。",
});
}
break;
case "birthday":
if (values[name]) {
setErrorMessage({ ...errorMessage, birthday: "" });
}
break;
}
}
}
When I test this, the setErrorMessage
of the first case does not trigger. I check the state in the dev tools, and it does not update.
It only updates the second case.
I inserted a console.log
in the first case (inside the if
statement), and it logs, proving that it is getting there. But somehow it is not updating the errorMessage
.
Is there something wrong in my code (syntax, etc.)?
Somebody knows what is wrong here?
Any help would be much appreciated.
Thanks in advance
2
Answers
Seems like you are not updating the
errorMessage
state correctly in the first case of your switch statement. Instead of spreading the currenterrorMessage
state, you are overwriting it with the new value.This may fix that:
Inside the loop you are overwriting the entire
errorMessage
object. Instead of updating just that specific error message for just that input being checked.You could update each error message separately using the
input name
as thekey
:By using the
newErrorMessage
it will update each error message inside the loop. After the loop is finished, we callsetErrorMessage
with thenewErrorMessage
object, which will update the error messages in the state.