Newer
Older
import {Link} from "react-router-dom";
import logo from './logo.png';
import cookie from 'react-cookies';
import React, { useEffect, useState, useContext} from 'react';
import { useNavigate, Navigate } from "react-router-dom";
import { UserContext } from './Usercontext.js';
import axios from 'axios';
axios.defaults.withCredentials = true;
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
function Welcome(props){
return (
<p>
{props.name?`${props.name}님, 환영합니다`:'로그인하세요.'}<br/>
</p>
)
}
function ButtonLink({link, onclick, children}){
return (
<botton onClick = {()=>{
onclick(link)}}>
{children}
</botton>
)
}
function Header({user}){
//console.log(cookie.load('name'))
const [currentSession, setCurrentSession] = useState(false)
const setUserName = useContext(UserContext);
const navigate = useNavigate();
function checkSession_And_Navigate(link){
if (cookie.load('name')) {
navigate(link);
setCurrentSession(true)
}
else {
setUserName(null)
if (currentSession){
alert('세션이 만료되었습니다. 로그인 후 이용해 주세요.')
}
else {
alert('로그인 후 이용해 주세요.')
}
navigate("/login");
setCurrentSession(false)
}
}
function dont_CheckSession_And_Navigate(link){
if (cookie.load('name')) {
setCurrentSession(true)
}
else {
setUserName(null)
if (currentSession){
alert('세션이 만료되었습니다. 자동으로 로그아웃됩니다.')
}
setCurrentSession(false)
}
navigate(link);
}
function logOut(){
let response = requestLogout();
if (response){
setUserName(null)
alert('로그아웃되었습니다. 메인 화면으로 돌아갑니다..')
setCurrentSession(false)
navigate('/');
}
}
<ButtonLink link='/' onclick={dont_CheckSession_And_Navigate}>
<img className="logo_image" alt="logo" src={logo}/>
</ButtonLink>
<ul>
<Welcome name={user}></Welcome>
<ul className="menu_list">
<li><ButtonLink link='/' onclick={dont_CheckSession_And_Navigate}>Home</ButtonLink></li>
<li><ButtonLink link='/search' onclick={checkSession_And_Navigate}>검색</ButtonLink></li>
<li><ButtonLink link='/postwrite' onclick={checkSession_And_Navigate}>포스트 작성</ButtonLink></li>
<li><ButtonLink link='/login' onclick={user?logOut:dont_CheckSession_And_Navigate}>{user?'로그아웃':'로그인'}</ButtonLink></li> {/*로그인 여부 로직 구현 필요*/}
{/* { Object.keys(user).length != 0 ?
<li><Link to={`/profile/${getUserId()}`}>profile</Link>/<span onClick={logout}>logout</span></li> :
<li><Link to="/login">login</Link></li>
} */}
</ul>
</ul>
async function requestLogout() {
const response = await axios({
url: 'http://localhost:8080/logout', // 통신할 웹문서
method: 'get', // 통신할 방식
});
if (response.status === 200) {
return response.data;
}
else {
return null;
}
}