Skip to content
This repository has been archived by the owner on Sep 19, 2021. It is now read-only.

[3주차] 고은 미션 제출합니다. #4

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 35 additions & 36 deletions src/components/login-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,71 +5,70 @@ import axios from 'axios';
import VoteForm from './vote-form';

export default function LoginForm() {
const [logForm, setLogForm] = useState({ email: '', password: '' });
const [isloged, setloged] = useState(false);
const [LoginForm, setLoginForm] = useState({ email: '', password: '' });
const [isloggedIn, setloggedIn] = useState(false);

const erasePW = () => {
document.getElementById('password').value = '';
};

const eraseEmail = () => {
document.getElementById('email').value = '';
const erase = (name) => () => {
setLoginForm({
...loginForm,
[name]: '',
});
};

const handleFormChange = (e) => {
setLogForm({ ...logForm, [e.target.id]: e.target.value });
setLoginForm({ ...LoginForm, [e.target.name]: e.target.value });
};

const handleSubmit = (logForm) => {
const { email, password } = logForm;
const handleSubmit = () => {
const { email, password } = LoginForm;
if (email === '' || password === '') {
alert('모든 항목을 입력해주세요!');
return false;
} else {
axios
.post(process.env.API_HOST + '/auth/signin/', logForm)
.then(function (response) {
console.log(response);
setloged(true);
alert('로그인 성공!');
})
.catch(function (error) {
if (error.response.status === 404) {
console.log('unauthorized, logging out ...');
alert('이메일이 존재하지 않습니다.');
eraseEmail();
erasePW();
} else if (error.response.status === 422) {
alert('비밀번호가 일치하지 않습니다!');
erasePW();
}
return Promise.reject(error.response);
});
}

axios
.post(process.env.API_HOST + '/auth/signin/', LoginForm)
.then((response) => {
console.log(response);
setloggedIn(true);
alert('로그인 성공!');
})
.catch((error) => {
if (error.response.status === 404) {
alert('이메일이 존재하지 않습니다.');
erase('email')();
erase('password')();
}
if (error.response.status === 422) {
alert('비밀번호가 일치하지 않습니다!');
erase('email')();
}
return Promise.reject(error.response);
});
};

return (
<div>
{!isloged && (
{!isloggedIn && (
<Wrapper>
<Title>로그인</Title>
<Row>
<Label>EMAIL</Label>
<Input type="text" id="email" onChange={handleFormChange}></Input>
<Input type="text" name="email" onChange={handleFormChange}></Input>
</Row>
<Row>
<Label>PASSWORD</Label>
<Input
type="password"
onChange={handleFormChange}
id="password"
name="password"
></Input>
</Row>
<Button onClick={() => handleSubmit(logForm)}>로그인</Button>
<Button onClick={() => handleSubmit()}>로그인</Button>
</Wrapper>
)}

{isloged && <VoteForm />}
{isloggedIn && <VoteForm />}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VoteForm이 LoginForm 내부에 있네요 😅
분리해주세요!

</div>
);
}
Expand Down
34 changes: 14 additions & 20 deletions src/components/vote-form.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import axios from 'axios';
import styled from 'styled-components';

function VoteForm() {
const [candi, setCandi] = useState([]);
const [candidates, setCandidates] = useState([]);
const [voteCount, setVoteCount] = useState();
Copy link
Member

@greatSumini greatSumini Apr 18, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 state가 사용되지 않고 있어요!, vote시 paramter로 넘겨줄 필요가 없기 때문에 지워주시면 될 것 같아요!

Suggested change
const [voteCount, setVoteCount] = useState();


useEffect(() => {
Expand All @@ -13,45 +13,42 @@ function VoteForm() {

const getCandidates = async () => {
await axios
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const getCandidates = async () => {
await axios
const getCandidates = axios

이렇게 바꿔줘도 의미가 같습니다! axios가 비동기 함수이기 때문이죠

.get(process.env.API_HOST + '/candidates/', candi)
.get(process.env.API_HOST + '/candidates/', candidates)
.then(({ data }) => {
setCandi(data);
setCandidates(data);
})
.catch(function (error) {
.catch((error) => {
console.log(error);
});
};

const voteCandidates = async (person) => {
const newUrl =
process.env.API_HOST + '/candidates/' + person._id + '/vote/';
const voteCandidates = async (candidate) => {
const newUrl = `${process.env.API_HOST}/candidates/${candidate._id}/vote/`;
await axios
.put(newUrl, voteCount)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.put(newUrl, voteCount)
.put(newUrl)

request body schema가 명시되지 않은 경우, 안 넘겨주셔도 됩니다!

.then(({ data }) => {
setVoteCount(data);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
setVoteCount(data);

삭제해주시면 됩니다 ㅎㅎ

alert(person.name + '님에게 투표 완료!');
alert(candidate.name + '님에게 투표 완료!');
getCandidates();
})
.catch(function (error) {
console.log(error);
alert('투표 실패!');
});
};
let i = 1;

return (
<Wrapper>
<Title>
<RedTitle>프론트엔드 인기쟁이</RedTitle>는 누구?
</Title>
<SubTitle>CEOS 프론트엔드 개발자 인기 순위 및 투표 창입니다.</SubTitle>
<VoteArea>
{candi
.sort((person1, person2) => {
return person2.voteCount - person1.voteCount;
})
.map((person) => (
<Row key={JSON.stringify(person)}>
<Rank>{i++}위:</Rank>
{candidates
.sort((person1, person2) => person2.voteCount - person1.voteCount)
.map((person, index) => (
<Row key={person._id}>
<Rank>{index + 1}위:</Rank>
<CandiName>
{person.name}
<br />[{person.voteCount}표]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

candidate-card.js 이름으로 새 파일을 만들어서, CandidateCard라는 새로운 컴포넌트 작성한 뒤에
이 부분에서 아래와 같이 쓸 수 있도록 리팩토링 해보는건 어떨까요?

Suggested change
.map((person, index) => (
<Row key={person._id}>
<Rank>{index + 1}위:</Rank>
<CandiName>
{person.name}
<br />[{person.voteCount}]
.map((candidate, index) => (
<CandidateCard {...candidate} />
))

Expand All @@ -63,10 +60,7 @@ function VoteForm() {
</Wrapper>
);
}
export default React.memo(
VoteForm,
(prev, next) => prev.voteCount === next.voteCount
);
export default React.memo(VoteForm);
const Row = styled.div`
display: flex;
flex-direction: row;
Expand Down