[TIL]230628

이세령·2023년 6월 28일
0

TIL

목록 보기
41/118

로그인 성공 시 보고있던 페이지로 이동하기

동작을 찾아보다가 useHistory Hook이 존재하는데 과거버전이라서 useNavigate를 사용하면 된다고 한다.

  • useLocation Hook
    이전 페이지에서 특정 값을 담아 넘겨줄 수 있기 때문에 이를 활용하여 이전에 담겨있던 param값을 넘겨주면 될 것 같다.
onClick={() => {
              navigate('/login', { state: { preURL: '/' } });
            }}

메인 페이지에서 로그인 버튼을 입력했을 때 넘겨주는 데이터이다.
state라는 key값으로 preURL 이라는 value를 넘겨주는데 이것을 사용해서 전에 있던 페이지로 돌아가는 동작을 만들었다.

로그인, 회원가입 예외처리

로그인

const signIn = async (event) => {
    event.preventDefault();
    try {
      const userCredential = await signInWithEmailAndPassword(auth, email, password);
      console.log(userCredential);

      const newUser = {
        email: auth.currentUser.email,
        uid: auth.currentUser.uid,
        displayname: auth.currentUser.displayName,
        photoURL: auth.currentUser.photoURL
      };

      dispatch(setUser(newUser));
      handleLocation();
    } catch (error) {
      switch (error.code) {
        case 'auth/user-not-found':
          alert('이메일이 일치하지 않습니다.');
          break;
        case 'auth/wrong-password':
          alert('비밀번호가 일치하지 않습니다.');
          break;
        default:
          alert('로그인에 실패 했습니다.');
          break;
      }
    }
  };

회원가입

const signUp = async (event) => {
    event.preventDefault();
    if (password !== confirmPassword) {
      alert('비밀번호가 일치하지 않습니다.');
      return; // 비밀번호 불일치 에러 처리 후 함수 종료
    } else if (displayName === '') {
      alert('닉네임을 입력해주세요');
      return;
    } else {
      try {
        const userCredential = await createUserWithEmailAndPassword(auth, email, password);
        const user = userCredential.user;
        // displayName 업데이트
        await updateProfile(user, {
          displayName: displayName
        })
          .then(() => {
            alert('회원가입이 완료되었습니다.');
            navigate('/login');
          })
          .catch((error) => {
            console.error('displayName 업데이트 중 오류:', error);
          });
      } catch (error) {
        const errorCode = error.code;

        console.log(errorCode);
        switch (errorCode) {
          case 'auth/invalid-email':
            alert('이메일을 입력해주세요');
            break;
          case 'auth/missing-password':
            alert('비밀번호를 입력해주세요');
            break;
          default:
            alert('회원가입에 실패했습니다.');
            break;
        }
      }
    }
  };

auth 정보 redux로 관리하기

  1. 로그인 했을 때 사용자 정보를 마이페이지, 게시글 등등 활용하기 때문에 redux에 저장한다.
  2. redux에 정보가 담겨있으면 로그인 페이지를 들어가지 못하게 해야한다.
  3. 로그아웃 시, redux의 정보를 제거한다.
  4. 브라우저 창을 닫을 때 redux의 정보도 같이 제거하고 로그아웃을 해야한다.

공통 스타일

styled-component를 사용할 때 공통되는 스타일은 상속받아서 사용할 수 있다.

const commonButton = styled.button`
  background-color: #eb9307;
  color: white;
  font-weight: 600;
  font-size: 0.9rem;
  &:hover {
    cursor: pointer;
    background-color: #ff8f05;
    color: black;
  }
`;
const LoginBtn = styled(commonButton)`
  width: 140px;
  height: 40px;
  border-radius: 14px;
  border: none;
`;
const MyPagebtn = styled(commonButton)``;

redux에 현재 유저 정보가 있으면 마이페이지 버튼 활성화하기

const [myPageButtonVisible, setmyPageButtonVisible] = useState(false);
  const user = useSelector((user) => user.currentuser);

  useEffect(() => {
    if (Object.keys(user).length !== 0) {
      setmyPageButtonVisible(true);
    }
  }, []);

</LoginBtn>
          {myPageButtonVisible && (
            <MyPagebtn
              onClick={() => {
                navigate('/mypage');
              }}
            >
              마이페이지
            </MyPagebtn>
          )}

렌더링 되었을 때 현재 로그인되어있는 정보가 있으면 마이페이지 버튼을 활성화 해주었다.

내일은 마이페이지 본인이 작성한 게시물, 마이페이지 프로필 수정 부분을 구현해야겠다.

profile
https://github.com/Hediar?tab=repositories

0개의 댓글