인프런, 유데미/Slack 클론 코딩
로그인 페이지 실행 로직
5_hyun
2022. 7. 20. 18:47
반응형
로그인 페이지 실행 로직
코드만 보면서 어떻게 돌아갈건지 예측하는 것도 좋은 연습 방법이다.
import useInput from '@hooks/useInput';
import { Success, Form, Error, Label, Input, LinkContainer, Button, Header } from '@pages/SignUp/styles';
import fetcher from '@utils/fetcher';
import axios from 'axios';
import React, { useCallback, useState } from 'react';
import { Link, Redirect } from 'react-router-dom';
import useSWR from 'swr';
const LogIn = () => {
const { data, error, mutate } = useSWR('http://localhost:3095/api/users', fetcher);
const [logInError, setLogInError] = useState(false);
const [email, onChangeEmail] = useInput('');
const [password, onChangePassword] = useInput('');
const onSubmit = useCallback(
(e: any) => {
e.preventDefault();
setLogInError(false);
axios
.post('/api/users/login', { email, password }, { withCredentials: true })
.then(() => {
mutate();
})
.catch((error) => {
setLogInError(error.response?.data?.statusCode === 401);
});
},
[email, password],
);
if (data) {
return <Redirect to="/workspace/channel" />;
}
return (
<div id="container">
<Header>Sleact</Header>
<Form onSubmit={onSubmit}>
<Label id="email-label">
<span>이메일 주소</span>
<div>
<Input type="email" id="email" name="email" value={email} onChange={onChangeEmail} />
</div>
</Label>
<Label id="password-label">
<span>비밀번호</span>
<div>
<Input type="password" id="password" name="password" value={password} onChange={onChangePassword} />
</div>
{logInError && <Error>이메일과 비밀번호 조합이 일치하지 않습니다.</Error>}
</Label>
<Button type="submit">로그인</Button>
</Form>
<LinkContainer>
아직 회원이 아니신가요?
<Link to="/signup">회원가입 하러가기</Link>
</LinkContainer>
</div>
);
};
export default LogIn;
1. 로그인 페이지에 왔을 때
const { data, error, mutate } = useSWR('http://localhost:3095/api/users', fetcher);
이 코드가 바로 실행된다. 처음엔 로그인을 안해서 data가 false이다. 따라서 return 부분이 화면에 뜬다.
2. 로그인을 했을 때
const onSubmit = useCallback(
(e: any) => {
e.preventDefault();
setLogInError(false);
axios
.post('/api/users/login', { email, password }, { withCredentials: true })
.then(() => {
mutate();
})
.catch((error) => {
setLogInError(error.response?.data?.statusCode === 401);
});
},
[email, password],
);
로그인 버튼을 누르면 onSubmit이 실행된다. 그리고 axios 요청을 보낸다. 로그인에 성공하면 mutate 함수가 실행되고 mutate가 실행되는 순간
const { data, error, mutate } = useSWR('http://localhost:3095/api/users', fetcher);
이 코드가 다시 실행된다. 그리고 data가 false에서 "내 정보"로 바뀐다. 이것을 보면 data나 error가 바뀌면 알아서 화면이 리렌더링된다.
3. 로그인에 성공해서 data에 "내 정보"가 있을 때
화면이 리렌더링돼서
if (data) {
return <Redirect to="/workspace/channel" />;
}
이 코드가 실행되고 workspace/channel로 이동한다. 그리고 이런 return은 항상 hooks 아래 있어야한다.
반응형