브라우저의 Console 창에서 localStorage.setItem을 설정했을 때 브라우저의 application 창에서 Local Storage 페이지를 보면 내가 setItem을 통해 설정한 값인 localStorage.setitem(“min”, true) 값이 저장되어 있는 것을 알 수 있다.
새로 고침을 해도 여전히 저장된 것을 확인할 수 있다.
api 호출 테스트
작업 순서
1. Email input : onChange
2. setState
3. Password input : onChange
4. setState
5. Button : onClick
6. fetch
7. Response 응답
import React from 'react';
import './Login.scss';
const API = "http://10.58.4.40:8000/user/signup”;
// 백엔드에서 준 API 주소를 변수로 지정하였다.
class LoginTeta extends React.Component {
// state 상태 초기설정
constructor() {
super();
this.state = {
userId: "",
userPw: “",
};
}
// input state 상태 변경 => setState
handleInput = (e) => {
const { name, value } = e.target;
// 1. e.target 이 반복되기 때문에 변수로 설정해주면
this.setState({
[name]: value
// 2. [e.target.name]: e.target.value 를 함축해서 쓸수 있다.
})
}
// ====== button login : 백엔드에 요청 시작 ======
handleClick = (e) => {
e.preventDefault()
// form tag 때문에 preventDefault()로 막아줘야함.
fetch(API, {
method: "POST",
body: JSON.stringify ({
// JSON 을 string으로 변환시켜주는 메소드 함수
email: this.state.userId,
password: this.state.userPw,
mobile: "01000000000",
full_name: "tetaMin",
username: "tetaMin”,
// key 값은 백엔드에서 넘겨준 key 값과 동일하게 작성해야 한다.
}),
}) // ====== button login : 백엔드에 요청 끝 ======
.then((response) => response.json())
// reponse : fetch의 return 값을 의미 string
.then((result) => {
// result : response.json()의 return 을 의미 Obj
console.log("=============");
console.log("백엔드에서 오는 응답 메세지 ", result);
// 성공 MESSAGE(백엔드에서 정해준 값)가 “REGISTER_SUCCESS”(백엔드에서 정해준 메세지) 이면
// main page로 넘어가가게 조건을 설정하였다.
if(result.MESSAGE === "REGISTER_SUCCESS") {
localStorage.setItem (“token”, result.Authorization);
// 로그인에 성공하면 local storage에 “token”을 “key” 값으로
// result.Authorization 를 value 값으로 저장한다는 뜻
this.props.history.push('/main-jiyeon');}
// main page로 이동한다.
});
}
// main page 이동
goToMain = () => {
this.props.history.push('/main-jiyeon');
}
render() {
// 반복되는 값을 변수로 지정해줘서 식 안에서 생략 가능하도록 하였다.
const { userId, userPw } = this.state;
const { handleInput } = this;
return (
<section>
<div className="container">
<div className="flex_box">
<h1 className="img_box">
<img className="logo_img" src="images/jiyeonmin/logo_text.png" alt="insta_logo" />
</h1>
<form className="login_form">
<div className="content">
<input name="userId" onChange={handleInput} id="login_ID" type="text" required placeholder="전화번호, 사용자 이름 또는 이메일" />
<input name="userPw" onChange={handleInput} id="login_PASS" type="password" required placeholder="비밀번호" />
<button className={ userId.includes("@") && userPw.length > 7 ? "login_BTN blue_BTN" : "login_BTN" } onClick={ this.handleClick }>로그인</button>
</div>
</form>
<span className="login_Q">
비밀번호를 잊으셨나요?
</span>
</div>
</div>
</section>
)
}
}
export default LoginTeta;