비동기 처리로 인한 버그 해결

김병화·2023년 8월 17일
0

Arch

목록 보기
11/14

로그인 에러 처리 기능을 구현하던 중 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를 새로 선언하여 setErrorsinitialErrors를 복사한다.

0개의 댓글

관련 채용 정보