Skip to content

Commit

Permalink
[fix/58]:과목 편집 api인스턴스 중복코드 삭제
Browse files Browse the repository at this point in the history
  • Loading branch information
doyi0107 committed Aug 25, 2024
2 parents c1a3ebf + b02bf68 commit 003d396
Show file tree
Hide file tree
Showing 16 changed files with 315 additions and 208 deletions.
15 changes: 4 additions & 11 deletions api/subjectFormApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,11 @@ interface SubjectPayload {
}

export const subjectFormApi = async (payload: SubjectPayload) => {
try {

const requestBody: { addedSubjects: string[]; deletedSubjects: number[] } = {
addedSubjects: [], // 기본값으로 빈 배열 설정
deletedSubjects: [], // 기본값으로 빈 배열 설정
};
console.log('API 요청 데이터:', payload);

// 추가된 과목이 있으면 requestBody에 추가, 빈 배열일 때는 빈 배열만 전송
if (payload.addedSubjects.length >= 0) {
Expand Down Expand Up @@ -41,10 +40,7 @@ export const subjectFormApi = async (payload: SubjectPayload) => {
}

return { success: true };
} catch (error) {
console.error('subjectFormApi 에러:', error);
return { success: false, message: '요청을 처리하는 중 오류가 발생했습니다. 나중에 다시 시도해 주세요.' };
}

};

interface Subject {
Expand All @@ -57,16 +53,13 @@ interface SubjectsResponse {
}

export const fetchSubjects = async (): Promise<SubjectsResponse> => {
try {

const response = await instance('timer', { method: 'GET' });

if (response.error) {
throw new Error('Error fetching subjects: ' + response.error.message);
}

return response;
} catch (error) {
console.error('Error in fetchSubjects:', error);
throw error;
}

};
6 changes: 6 additions & 0 deletions app/mypage/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import SmallButton from '@/components/common/SmallButton';
import Cookies from 'js-cookie';
import { signOut } from '@/api/authApi';
import { useRouter } from 'next/navigation';
import { useUserInfoStore } from '@/store/memberStore';

export default function Layout({ children }: { children: React.ReactNode }) {
const route = useRouter();
const { setUserInfo } = useUserInfoStore();

const logoutHandler = async () => {
// 로그아웃할건지 확인하는 모달창 띄우기
Expand All @@ -20,6 +22,10 @@ export default function Layout({ children }: { children: React.ReactNode }) {
Cookies.remove('access_token');
Cookies.remove('refresh_token');

// 유저 정보 삭제
localStorage.removeItem('userInfo');
setUserInfo(null);

route.push('/login');
};

Expand Down
1 change: 1 addition & 0 deletions app/mypage/subjectedit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default function Page() {
height: '60px',
fontWeight: '700',
};

return (
<SubjectEditForm
onSaveEditing={() => {
Expand Down
12 changes: 0 additions & 12 deletions app/ranking/ranking.module.css → app/ranking/page.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,6 @@
0 6px 14px rgba(0, 0, 0, 0.1); */
}

.top_rankings_wrap {
width: 100%;
display: flex;
justify-content: center;
padding: 30px 0px;
}

.btm {
/* width: 100%;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1),
Expand Down Expand Up @@ -77,11 +70,6 @@
font-size: var(--font-size-3);
}

.top_rankings_wrap {
width: auto;
padding: 5px 0px;
}

.full_ranking_wrap {
border-top-left-radius: 50px;
border-top-right-radius: 50px;
Expand Down
52 changes: 24 additions & 28 deletions app/ranking/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
'use client';
import React, { useEffect, useState, useCallback } from 'react';
import TopRankings from '@/components/ranking/topLanking';
import TopRankings from '@/components/ranking/topRanking';
import FullRankingList from '@/components/ranking/fullRankingList';
import { Box, Flex, Grid } from '@radix-ui/themes';
import styles from './ranking.module.css';
import styles from './page.module.css';
import rankingImg from '@/assets/icons/ranking_profile_img.png';
import { fetchRankingsAndCurrentUserFromServer } from '@/api/rankingApi';
import { Student, ApiResponse } from '@/types/rankingType';
Expand All @@ -22,32 +22,28 @@ export default function Ranking() {
setPage(0);
setHasMore(true);

try {
const {
member,
ranking: { ranks: initialRankings, hasNext },
}: ApiResponse = await fetchRankingsAndCurrentUserFromServer({
tab: activeTab,
pageNumber: 0,
size,
});
const {
member,
ranking: { ranks: initialRankings, hasNext },
}: ApiResponse = await fetchRankingsAndCurrentUserFromServer({
tab: activeTab,
pageNumber: 0,
size,
});

const currentUserData: Student = {
id: member.id,
name: member.name,
studyTime: member.studyTime,
totalTime: member.totalTime,
course: member.course,
rank: member.rank,
image: member.image || rankingImg,
};
const currentUserData: Student = {
id: member.id,
name: member.name,
studyTime: member.studyTime,
totalTime: member.totalTime,
course: member.course,
rank: member.rank,
image: member.image || rankingImg,
};

setRankings(initialRankings);
setHasMore(hasNext);
setCurrentUser(currentUserData);
} catch (error) {
console.error('Error fetching data:', error);
}
setRankings(initialRankings);
setHasMore(hasNext);
setCurrentUser(currentUserData);
};

fetchData();
Expand Down Expand Up @@ -109,9 +105,9 @@ export default function Ranking() {
</ul>
</Flex>
</Box>
<Grid className={styles.top_rankings_wrap}>
<Box pb="5" className={styles.top_rankings_wrap}>
<TopRankings rankings={rankings} activeTab={activeTab} />
</Grid>
</Box>
</Box>
<Box p="5" pr="3" className={styles.btm}>
<FullRankingList
Expand Down
14 changes: 14 additions & 0 deletions components/auth/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ import { Box, Text } from '@radix-ui/themes';
import AuthFormLayout from './AuthFormLayout';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { getUserInfo } from '@/api/memberApi';
import Cookies from 'js-cookie';
import useSWR from 'swr';
import { useUserInfoStore } from '@/store/memberStore';

interface LoginFormProps {
onLogin: (email: string, password: string) => Promise<Response>;
Expand Down Expand Up @@ -37,6 +41,16 @@ export default function LoginForm({ onLogin }: LoginFormProps) {
}
};

// 유저정보조회
const accessToken = Cookies.get('access_token');
const { setUserInfo } = useUserInfoStore();
const { data } = useSWR(accessToken ? ['userInfo'] : null, async () => {
const result = await getUserInfo();
const storedUserInfo = { name: result.name, course: result.course, image: result.image };
localStorage.setItem('userInfo', JSON.stringify(storedUserInfo));
setUserInfo(storedUserInfo);
});

return (
<AuthFormLayout title="로그인">
<form onSubmit={handleLogin}>
Expand Down
57 changes: 34 additions & 23 deletions components/common/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ import Image from 'next/image';
import Cookies from 'js-cookie';
import { API_ROUTE_URL } from '@/constants/url';
import useSWR from 'swr';
import useUserInfo from '@/hook/useUserInfo';
import { useUserInfoStore } from '@/store/memberStore';

export default function Header() {
useSWR('reissue-token', revaildateToken);
const { setUserInfo } = useUserInfoStore();

// eslint-disable-next-line func-style
async function revaildateToken() {
Expand All @@ -38,11 +41,17 @@ export default function Header() {

// 토큰을 성공적으로 재발급받은 후 페이지 리로드
window.location.reload();

return data;
}

if (!accessToken && !refreshToken) {
localStorage.removeItem('userInfo');
setUserInfo(null);
}
}

const userInfo = useUserInfo();

return (
<Box px="5" asChild>
<header className={styles.header}>
Expand All @@ -55,28 +64,30 @@ export default function Header() {
<nav className={styles.gnb}>
<HeaderNav />
</nav>
<div className={styles.user_info}>
<Flex align="center" gap="2" asChild>
<Link href="/mypage">
<div
className={styles.user_name}
style={{
// 유저 프로필 이미지
backgroundImage: `url('')`,
}}
>
{/* 기본 이미지 */}
<Image src={rankingImg} alt={`프로필 이미지`} width={40} height={40} />
</div>
<div className={styles.user_txt}>
<Strong>홍길동</Strong>
<Text as="p" size="2" mt="1" weight="medium">
클라우드 서비스
</Text>
</div>
</Link>
</Flex>
</div>
{userInfo && (
<div className={styles.user_info}>
<Flex align="center" gap="2" asChild>
<Link href="/mypage">
<div
className={styles.user_name}
style={{
// 유저 프로필 이미지
backgroundImage: `url('')`,
}}
>
{/* 기본 이미지 */}
<Image src={rankingImg} alt={`프로필 이미지`} width={40} height={40} />
</div>
<div className={styles.user_txt}>
<Strong>{userInfo?.name}</Strong>
<Text as="p" size="2" mt="1" weight="medium">
{userInfo?.course}
</Text>
</div>
</Link>
</Flex>
</div>
)}
</Box>
</header>
</Box>
Expand Down
9 changes: 6 additions & 3 deletions components/mypage/UserProfile.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
'use client';

import { Avatar, Box, Strong, Text } from '@radix-ui/themes';
import { Box, Strong, Text } from '@radix-ui/themes';
import { useRef, useState } from 'react';
import styles from './UserProfile.module.css';
import ico_profile_img_file from '@/assets/icons/profile_img_file.png';
import Image from 'next/image';
import MypageTabMenu from './MypageTabMenu';

import rankingImg from '@/assets/icons/ranking_profile_img.png';
import useUserInfo from '@/hook/useUserInfo';

export default function UserProfile() {
const [imgUrl, setImgUrl] = useState('');
Expand Down Expand Up @@ -39,6 +40,8 @@ export default function UserProfile() {
}
};

const userInfo = useUserInfo();

return (
<section className="user_profile">
<div className={styles.user_info}>
Expand All @@ -56,9 +59,9 @@ export default function UserProfile() {
</div> */}
</div>
<Box mt="3" className={styles.txt_box}>
<Strong>홍길동</Strong>
<Strong>{userInfo?.name}</Strong>
<Text as="p" size="3" weight="medium">
클라우드 서비스
{userInfo?.course}
</Text>
</Box>
</div>
Expand Down
Loading

0 comments on commit 003d396

Please sign in to comment.