Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[김미소] week14 #445

Merged
merged 21 commits into from
May 21, 2024
Merged
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
d6de20f
Merge branch 'part3-김미소' into part3-김미소-week13
nightowlzz May 13, 2024
569075d
Feat: 메인페이지 React에서 Next.js로의 전환과 관련된 작업 추가 및 수정
nightowlzz May 13, 2024
97ad057
Feat: 특정페이지 header, footer 노출 유무 작업
nightowlzz May 14, 2024
c28130d
Feat: 로그인, 회원가입 JS파일 Next.js로 이동 및 오류수정
nightowlzz May 14, 2024
2259ce3
Feat: 회원가입 react-hook-form 적용 및 중복확인 작업
nightowlzz May 16, 2024
3a2d697
Feat: 로그인 페이지 react-hook-form 적용 및 가입확인 api 연동
nightowlzz May 16, 2024
9268e71
Move: pages폴더 안에있던 style 위치이동 및 로그인,회원가입 로그인지 접속제한
nightowlzz May 16, 2024
eba660c
Feat: 로그인 유무에 따라 header의 유저정보 보이기
nightowlzz May 16, 2024
bcc432c
Rename: login => signin으로 이름변경 및 input eorror 클래스 추가
nightowlzz May 16, 2024
248039b
Fix: 페이지확인 하면 오류 수정
nightowlzz May 16, 2024
8c0d0a9
Fix: prettier, eslint 설치하고 코드라인 정리
nightowlzz May 16, 2024
0ab9e90
Fix: 코드리뷰 받은 것들 수정
nightowlzz May 16, 2024
ff1514b
Refactor: 로그인시 접근제한 cookie인증으로 수정, redirect로 페이지 이동
nightowlzz May 18, 2024
59de712
Refactor: header, footer 특정페이지 접근히 노출 제한
nightowlzz May 18, 2024
ba0dc40
Fix: 이미지 주소 변수명 변경
nightowlzz May 18, 2024
bd9b2e6
Fix: boolean 변수 이름 변경
nightowlzz May 18, 2024
184bce6
Fix: getServerSideProps let을 const로 변경하기 위한 구조변경
nightowlzz May 18, 2024
0453cae
Fix: 로그인시 url입력 이동하면 유저정보가 로그인버튼이 노출되는 에러 수정
nightowlzz May 18, 2024
61fd9d4
Refactor: <img/> 태그를 nextjs <Image/>로 변경
nightowlzz May 18, 2024
73d070d
Refactor: Modal전체 구조 변경
nightowlzz May 18, 2024
87bd07a
Refactor: 로딩 화면 추가
nightowlzz May 19, 2024
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
Prev Previous commit
Next Next commit
Feat: 로그인 유무에 따라 header의 유저정보 보이기
  • Loading branch information
nightowlzz committed May 16, 2024
commit eba660c0fbd466e49a294b26fca12fdd6ed802bc
60 changes: 33 additions & 27 deletions components/common/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { useContext, useEffect, useState } from "react";
import { instance } from "@/lib/axios";
import { Email, HeaderControl, HeaderInner, HeaderLogo, HeaderUserInfo, HeaderWrap } from "./headerStyle";
import { joinInstance } from "@/lib/axios";
import { Email, HeaderControl, HeaderInner, HeaderLogo, HeaderWrap } from "./headerStyle";
import { useRouter } from "next/router";
import { Profile } from "@/styles/commonStyle";
import LinkButton from "./atoms/LinkButton";
import Link from "next/link";
import Image from "next/image";
import { LayoutContext } from "@/lib/LayoutContext";
import { pageLayoutConfig, urlName } from "@/src/constant/layoutConfig";
import Button from "./atoms/Button";

const logo = '/assets/logo/logo.svg';

@@ -20,36 +20,42 @@ export interface IHeaderUser {
auth_id:string
}

export interface IHeaderUserLoginInfoApi {
userInfo?: {
data: IHeaderUser[];
};
}

export async function getStaticProps() {
const res = await instance.get(``);
const userInfo = res.data;

return {
props:{
userInfo,
}
}
}

function Header({userInfo}:IHeaderUserLoginInfoApi) {
function Header() {
const { pathname } = useRouter();
const results: urlName = pathname.split('/')[1];
const layoutConfig = pageLayoutConfig[results] || { header: true };
const {headerShow, setHeaderShow} = useContext(LayoutContext)
const {headerShow, setHeaderShow, isLoggedIn, setIsLoggedIn} = useContext(LayoutContext)
const [fixed, setFixed] = useState(true);
const [userInfo, setUserInfo] = useState<IHeaderUser | null>();

const handleUserinfo = async () => {
const res = await joinInstance.get(`/sample/user`);
Copy link
Collaborator

Choose a reason for hiding this comment

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

다음과 같이 구조분해할당을 할 수 있습니다 !

Suggested change
const res = await joinInstance.get(`/sample/user`);
const { data } = await joinInstance.get(`/sample/user`);

Copy link
Collaborator

Choose a reason for hiding this comment

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

보통 api 함수들은 따로 빼놓고 사용하는게 일반적입니다 ! 😊

Next.js 프로젝트에서는 API 호출 로직을 별도의 파일로 분리하여 관리하는 것이 일반적이예요. 이렇게 하면 코드의 재사용성을 높이고, 유지보수가 쉬워질 수 있습니다 ! API 함수를 모듈화하여 사용하면 코드가 더 깔끔하고 읽기 쉬워집니다. 다음은 Next.js 프로젝트의 디렉토리 구조와 API 함수 예제입니다:

// src/services/apis/user.api.ts (예시입니다 !)
export const getUserInfo = async () => {
  const response = await axios.get('/sample/user');
  return response.data;
};

setUserInfo(JSON.parse(JSON.stringify(res.data)));
Copy link
Collaborator

Choose a reason for hiding this comment

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

혹시 JSON 임베드 모듈을 사용하게 된 이유가 있으실까요? 🤔

}

const handleLogout = () => {
localStorage.removeItem('linkbrary');
if(setIsLoggedIn) setIsLoggedIn(false);
}

useEffect(() => { // 유저정보
handleUserinfo();
if(setIsLoggedIn) {
if(localStorage.getItem('linkbrary')){
setIsLoggedIn(true)
} else {
setIsLoggedIn(false)
}
}
},[])

useEffect(() => {
useEffect(() => { // 페이지 컴포넌트 유무
if (setHeaderShow) {
setHeaderShow(layoutConfig.header);
}
}, [pathname]);

if(!headerShow) return null;
return (
<HeaderWrap className="head__wrap" $position={fixed}>
@@ -60,11 +66,11 @@ function Header({userInfo}:IHeaderUserLoginInfoApi) {
</Link>
</HeaderLogo>
<HeaderControl className="head__login__box">
{userInfo ? (
<HeaderUserInfo>
{isLoggedIn ? (
<Button onclick={handleLogout}>
<Profile></Profile>
<Email>{userInfo?.data[0].email}</Email>
</HeaderUserInfo>
<Email>{userInfo?.email}</Email>
</Button>
) : (
<LinkButton $link={'/login'} $linkClass={'link--gradient link--login large'}>
로그인
2 changes: 1 addition & 1 deletion components/common/atoms/Button.tsx
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@ import { ButtonHTMLAttributes } from 'react';
import { ButtonModule } from './buttonStyle';
interface IButtonModule {
children: React.ReactNode;
$btnClass: string;
$btnClass?: string;
$BeforButtonIcon?: string;
$id?: string;
$afterButtonIcon?: string;
12 changes: 8 additions & 4 deletions components/common/headerStyle.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { DFlaxAlignCenter, DFlaxAlignCenterBtw } from "@/styles/commonStyle";
import { DFlaxAlignCenter, DFlaxAlignCenterBtw, dflexCenter } from "@/styles/commonStyle";
import { theme } from "@/styles/theme";
import styled from "styled-components";
import Button from "./atoms/Button";

export const HeaderWrap = styled.header<{$position:boolean | undefined}>`
position: ${({$position})=> $position ? 'fixed' : 'absolute'};
@@ -34,10 +35,13 @@ export const HeaderLogo = styled.h1`
}
}
`
export const HeaderControl = styled.div``
export const HeaderUserInfo = styled(DFlaxAlignCenter)`
gap: 0.375rem;
export const HeaderControl = styled.div`
button {
${dflexCenter};
gap: 0.375rem;
}
`

export const Email = styled.span`
color: ${theme.color.gray3};
@media screen and (max-width: ${theme.screenSize.moLarge}) {
2 changes: 1 addition & 1 deletion components/folder/PostCard.tsx
Original file line number Diff line number Diff line change
@@ -47,7 +47,7 @@ export default function PostCard({ image_source, description, created_at}: IFold
<figure>
<div className="card__image">
{image_source ? (
<Image fill src={image_source} alt={image_source} />
<Image fill src={image_source} alt={image_source} sizes="100% 100%"/>
) : (
<img className="empty" src={emptyImg} alt="" />
)}
11 changes: 8 additions & 3 deletions lib/LayoutContext.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
import React, { createContext, useState } from "react";

interface layoutContextType {
isLoggedIn?: boolean;
setIsLoggedIn?: (show: boolean) => void | undefined;
headerShow?: boolean;
setHeaderShow?: (show: boolean) => void | undefined;
footShow?:boolean;
setFootShow?: (show: boolean) => void | undefined;
}

export const LayoutContext = createContext<layoutContextType>({
headerShow: false,
isLoggedIn: false,
setIsLoggedIn: () => {},
headerShow: true,
setHeaderShow: () => {},
footShow: false,
footShow: true,
setFootShow: () => {},
});

export default function LayoutProvider({ children }:{ children:React.ReactNode }) {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [headerShow, setHeaderShow] = useState(true);
const [footShow, setFootShow] = useState(true);

return (
<LayoutContext.Provider value={{ headerShow, setHeaderShow, footShow, setFootShow }}>
<LayoutContext.Provider value={{ headerShow, setHeaderShow, footShow, setFootShow, isLoggedIn, setIsLoggedIn }}>
{ children }
</LayoutContext.Provider>
)
7 changes: 5 additions & 2 deletions pages/login/index.tsx
Original file line number Diff line number Diff line change
@@ -3,14 +3,16 @@ import { JoinBody, JoinAccessControlBox, JoinSocial, JoinTitle, JoinWrap } from
import LinkButton from "@/components/common/atoms/LinkButton";
import Button from "@/components/common/atoms/Button";
import { ErrorText, FormRowBox, FormWrap } from "@/components/join/formStyle";
import { useEffect, useState } from "react";
import { useContext, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { loginForm } from "@/components/join/interfase";
import { joinInstance } from "@/lib/axios";
import { useRouter } from "next/router";
import { LayoutContext } from "@/lib/LayoutContext";

export default function Login() {
const router = useRouter();
const {setIsLoggedIn} = useContext(LayoutContext)
const [visibility, setVisibility] = useState(false);
const {register, handleSubmit, formState: { errors }, setError} = useForm<loginForm>({ mode:'onBlur' });

@@ -19,7 +21,8 @@ export default function Login() {
const res = await joinInstance.post('/sign-in',{email, password});
const { data } = res;
if(data) {
localStorage.setItem('linkbrary', data.data.accessToken)
if(setIsLoggedIn) setIsLoggedIn(true);
localStorage.setItem('linkbrary', data.data.accessToken);
router.push('/folder');
}
} catch {
1 change: 1 addition & 0 deletions styles/commonStyle.ts
Original file line number Diff line number Diff line change
@@ -158,6 +158,7 @@ export interface IProfileImg {
}

export const Profile = styled.span<IProfileImg>`
display: block;
width: 28px;
height: 28px;
border-radius: 50em;