로그인 에러 처리 기능을 구현하던 중 React의 비동기적 특성로 인한 문제가 발생하였다.
const SignIn = () => {
const [errors, setErrors] = useState({
isIdInputEmpty: false,
isPwInputEmpty: false,
isIdNotFound: false,
isPwIncorrect: false,
});
const handleSubmit = (e: React.SyntheticEvent) => {
e.preventDefault();
// setErros 초기화가 안됨
setErrors({
isIdInputEmpty: false,
isPwInputEmpty: false,
isIdNotFound: false,
isPwIncorrect: false,
});
}
if (inputId === '') {
idInputRef.current?.focus();
setErrors({ ...erros, isIdInputEmpty: true });
} else if (inputPw === '') {
pwInputRef.current?.focus();
setErrors({ ...erros, isPwInputEmpty: true });
} else {
e.preventDefault();
setInputs({
id: '',
pw: '',
});
const checkInputId = users.find((user) => user.id === inputId);
if (checkInputId) {
if (checkInputId.pw === inputPw) console.log('로그인 성공!');
else {
setErrors({ ...erros, isPwIncorrect: true });
}
} else {
setErrors({ ...erros, isIdNotFound: true });
}
}
}
이 코드는 비동기적 처리 때문에 submit 시에 errors가 초기화되지 않는 문제가 발생하였다.
const SignIn = () => {
const [errors, setErrors] = useState({
isIdInputEmpty: false,
isPwInputEmpty: false,
isIdNotFound: false,
isPwIncorrect: false,
});
const handleSubmit = (e: React.SyntheticEvent) => {
e.preventDefault();
// initialErrors를 별도로 선언
const initialErrors = {
isIdInputEmpty: false,
isPwInputEmpty: false,
isIdNotFound: false,
isPwIncorrect: false,
};
}
if (inputId === '') {
idInputRef.current?.focus();
setErrors({ ...initialErrors, isIdInputEmpty: true });
} else if (inputPw === '') {
pwInputRef.current?.focus();
setErrors({ ...initialErrors, isPwInputEmpty: true });
} else {
e.preventDefault();
setInputs({
id: '',
pw: '',
});
const checkInputId = users.find((user) => user.id === inputId);
if (checkInputId) {
if (checkInputId.pw === inputPw) console.log('로그인 성공!');
else {
setErrors({ ...initialErrors, isPwIncorrect: true });
}
} else {
setErrors({ ...initialErrors, isIdNotFound: true });
}
}
}
initialErrors
를 새로 선언하여 setErrors 시 initialErrors
를 복사한다.