
환경 정리
// path : api/index.ts
export const SignInApi = async (data: any) => {
const response = await axios.post("http//localhost:4000/api/auth/signIn", data).catch((error) => return null);
if (!response) return null;
const result = response.data;
return result;
}
export const SignUpApi = async (data: any) => {
const response = await axios.post("http//localhost:4000/api/auth/signUp", data).catch((error) => return null);
if (!response) return null;
const result = response.data;
return result;
}
// path : views/Athentification/SignUp/index.tsx
import React from 'react'
export default function SignUp() {
const [userEmail, setUserEmail] = useState<string>('');
const [userPassword, setPassword] = useState<string>('');
const [userPasswordCheck, setUserPasswordCheck] = useState<string>('');
const [userNickname, setUserNickname] = useState<string>('');
const [userPhoneNumber, setUserPhoneNumber] = useState<string>('');
const [userGender, setUserGender] = useState<string>('');
const SignUpHandler = async () => {
const data = {
userEmail,
userPassword,
...
};
const signUpResponse = await SignUpApi(data);
if (!signUpResponse) {
alert('회원가입에 실패했습니다');
return;
}
alert('회원가입에 성공했습니다');
}
return (
{ user != null && (<>{user.userNickname}</>)}
<div>
<TextField fullWidth label="이메일 주소" type="email" variant="standart" onClick={(e) => setUserEmail(e.target.value)} />
</div>
)
}
// path : views/Athentification/SignIn/index.tsx
import React, { useState } from 'react';
import axios from "axios";
import { useCookies } from "react=cookie";
export default function SignIn() {
const [email, setEamil] = useState<string>('');
const [password, setPassword] = useState<String>('');
const [cookies, setCookies] = useCookies();
const {setUser} = useUserStore(); //store에 저장함으로써 외부에서 관리됨
const signInHandeler = async () => {
if (email.length === 0 || password.length === 0){
alert('이메일과 비밀번호를 입력하세요');
return;
}
const data = {
userEmail,
userPassword
}
const signInResponse = await signInApi(data);
if (!signInResponse) {alert('로그인에 실패했습니다.');}
if (!signInResponse.result) {
alert('로그인에 실패했습니다.');
return;
}
const { token, exprTime, user } = responseData.data;
const expires = new Date();
expires.setMillseconds(expires.getMilliseconds() + exprTime);
setCookies('token', token, { expires }); // token이 쿠키에 등록됨 (토큰이 쿠키에 유지되는 동안은 로그인 중이라고 이해 가능)
setUser(user);
}
return (
<div>Untitled-1</div>
)
}
쿠키에 유저 정보를 등록하고 전역 user를 등록하는 과정
const signInResponse = await signInApi(data);
if (!signInResponse) {alert('로그인에 실패했습니다.');}
if (!signInResponse.result) {
alert('로그인에 실패했습니다.');
return;
}
const { token, exprTime, user } = responseData.data;
const expires = new Date();
expires.setMillseconds(expires.getMilliseconds() + exprTime);
setCookies('token', token, { expires }); // token이 쿠키에 등록됨 (토큰이 쿠키에 유지되는 동안은 로그인 중이라고 이해 가능)
setUser(user);
const requestOption = {
headers: {
Authorization: `Bearer ${token}`
}
};
const data = {
// body 데이터 객체 형식으로 작성
diaryDetail
addDate
// ...
};
await axios.post("http://localhost:4000/api/board/", data, requestOption)
.then((response) => {
setBoardResponse(response.data);
})
.catch((error) => {
console.error(error);
});
// npm install react-cookie
// npm install zustand (보통 redux를 사용하는데 어려워서 이 강의에서 zustand 사용)
// stores/user.store.ts
import { create } from "zustand";
interface UserStore{
user : any;
setUser: (user: any) => void;
removeUser: () => void;
}
const useStore = create<UserStore>((set) => ({
user : null,
setUser: (user: any) => {
set((state) => ({...state, user}));
},
removeUser: () => {
set((state) => ({...state, user: null}));
},
}));
export default useStore
// stores/index.ts
import useUserStore from './user.store';
export {useUserStore};