#29,30 로그인 페이지
2022. 8. 4. 21:40ㆍTIL/따라하며 배우는 노드 리액트
728x90
[인프런] 따라하며 배우는 노드, 리액트 시리즈 - 기본강의를 들으며 정리한 내용입니다.
1. LandingPage.js 파일에 기본 스타일 적용
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "100%",
height: "100vh",
}}
>
시작 페이지
</div>
2. LoginPage.js에 로그인 폼 추가
import React, { useState } from "react";
export default function LoginPage() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const onEmailHandler = (e) => {
setEmail(e.target.value);
};
const onPasswordHandler = (e) => {
setPassword(e.target.value);
};
const onSubmitHandler = (e) => {
e.preventDefault();
const body = {
email: email,
password: password,
};
};
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
width: "100%",
height: "100vh",
}}
>
<form
onSubmit={onSubmitHandler}
style={{
display: "flex",
flexDirection: "column",
justifyContent: "center",
alignItems: "flex-start",
}}
>
<label htmlFor="email">email</label>
<input
type="email"
name="email"
id="email"
value={email}
onChange={onEmailHandler}
/>
<label htmlFor="password">password</label>
<input
type="password"
name="password"
id="password"
value={password}
onChange={onPasswordHandler}
/>
<br />
<button type="submit">Login</button>
</form>
</div>
);
}
3. actions/user_action.js 파일 추가
import axios from "axios";
import { LOGIN_USER } from "./types";
export function loginUser(dataToSubmit) {
const request = axios
.post("/api/users/login", dataToSubmit)
.then((response) => response.data);
return {
type: LOGIN_USER,
payload: request,
};
}
4. _actions/types.js 파일 추가
export const LOGIN_USER = "login_user";
5. _reducers/user_reducer.js 파일 추가
import { LOGIN_USER } from "../_actions/types";
export default function (state = {}, action) {
switch (action.type) {
case LOGIN_USER:
return { ...state, loginSuccess: action.payload };
default:
return state;
}
}
6. rootReducer에 user_reducer 추가 (_reducers/index.js)
import { combineReducers } from "redux";
import user from "./user_reducer";
const rootReducer = combineReducers({
user,
});
export default rootReducer;
7. LoginPage.js에 dispatch 적용
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { loginUser } from "../../../_actions/user_action";
export default function LoginPage() {
const dispatch = useDispatch();
const navigate = useNavigate();
const onSubmitHandler = (e) => {
e.preventDefault();
const body = {
email: email,
password: password,
};
dispatch(loginUser(body)).then((response) => {
if (response.payload.loginSuccess) {
navigate('/'); //로그인 완료시 메인페이지로 이동
} else {
alert("error");
}
});
};
...
}
'TIL > 따라하며 배우는 노드 리액트' 카테고리의 다른 글
#32 로그아웃 (0) | 2022.08.04 |
---|---|
#31 회원 가입 페이지 (0) | 2022.08.04 |
#26,27 Redux 기본 설정 (0) | 2022.08.04 |
#24 Concurrently (0) | 2022.08.04 |
#23 Proxy Server란? (0) | 2022.08.04 |