Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 4 additions & 2 deletions src/components/Header/DashboardHeader/MemberProfiles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ const genMemberProfiles = (members: Member[], distance: number) =>

// NOTE: 대시보드 헤더 구성원 프로필 목록 컴포넌트
export default function MemberProfiles({ id }: MemberProfilesProps) {
const { data, isLoading, error } = useFetchData<MembersResponse>(['members', id, 1], () =>
getMembersList(Number(id)),
const { data, isLoading, error } = useFetchData<MembersResponse>(
['members', id, 1],
() => getMembersList(Number(id)),
!!id,
);

if (isLoading) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/Header/DashboardHeader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default function DashboardHeader() {
data: dashboard,
isLoading,
error,
} = useFetchData<Dashboard>(['dashboard', id], () => getDashboard(id as string));
} = useFetchData<Dashboard>(['dashboard', id], () => getDashboard(id as string), !!id);

if (isLoading || !id) {
return <DefaultHeader title='로딩중...' />;
Expand Down
76 changes: 47 additions & 29 deletions src/components/Redirect/index.tsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,63 @@
import { useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import { useSelector } from 'react-redux';

import useRedirectIfAuth from '@/hooks/useRedirectIfAuth';
import useRedirectIfNotAuth from '@/hooks/useRedirectIfNotAuth';
import useRedirect from '@/hooks/useRedirect';
import { RootState } from '@/store/store';

// NOTE: 권한에 따라 페이지 이동
export default function Redirect({ children }: { children: React.ReactNode }) {
const router = useRouter();
const redirect = useRedirect();
const { user } = useSelector((state: RootState) => state.user);
const router = useRouter();
const currentPath = router.pathname;

const redirectIfAuth = useRedirectIfAuth();
const redirectIfNotAuth = useRedirectIfNotAuth();

// NOTE: 로그인 한 경우 mydashboard를 default로
if (currentPath === '/' && user) {
router.replace('/mydashboard');
}

// NOTE: 잘못된 주소 접근 시 3초 뒤 적절한 페이지로 이동
if (currentPath === '/404') {
const nextPath = user ? '/mydashboard' : '/';
setTimeout(() => router.push(nextPath), 3000);
}

// NOTE: 로그인한 사용자가 로그인/회원가입 접근 시 mydashboard로 이동
if (['/signup', '/signin'].includes(currentPath)) {
const isRedirecting = redirectIfAuth();
if (isRedirecting) {
return <></>;
// NOTE: QueryCache로 글로벌 콜백 설정
const queryClient = useQueryClient();
const queryCache = queryClient.getQueryCache();
queryCache.config = {
onError: (error) => {
if (error instanceof AxiosError) {
switch (error.response?.status) {
case 401:
redirect('/signin', '로그인이 필요합니다');
break;
case 403:
case 404:
if (user) redirect('/mydashboard', '접근 권한이 없습니다');
else redirect('/signin', '접근 권한이 없습니다');
break;
default:
throw error;
}
}
},
};

useEffect(() => {
// NOTE: 로그인 한 경우 mydashboard를 default로
if (currentPath === '/' && user) {
router.replace('/mydashboard');
}

// NOTE: 잘못된 주소 접근 시 3초 뒤 적절한 페이지로 이동
if (currentPath === '/404') {
const nextPath = user ? '/mydashboard' : '/';
setTimeout(() => router.push(nextPath), 3000);
}

// NOTE: 로그인/회원가입 - 로그인 O -> 내 대시보드
if (['/signup', '/signin'].includes(currentPath) && user) {
redirect('/mydashboard', '이미 로그인했습니다');
}
}

// TODO: 추후 리팩토링 예정
if (['/mypage', '/mydashboard'].includes(currentPath)) {
const isRedirecting = redirectIfNotAuth();
if (isRedirecting) {
return <></>;
// NOTE: 내 대시보드/계정관리 - 로그인 X -> 로그인
if (['/mypage', '/mydashboard'].includes(currentPath) && !user) {
redirect('/signin', '로그인이 필요합니다');
}
}
}, [currentPath, router.query.id]);

return children;
}
34 changes: 8 additions & 26 deletions src/containers/dashboard/ColumnsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,11 @@ import Column from './Column';

import useFetchData from '@/hooks/useFetchData';
import useModal from '@/hooks/useModal';
import useRedirectIfNotMember from '@/hooks/useRedirectIfNotMember';
import instance from '@/services/axios';
import { getColumnsList, getDashboard } from '@/services/getService';
import { getColumnsList } from '@/services/getService';
import { moveToOtherColumn } from '@/services/putService';
import { RootState } from '@/store/store';
import { ColumnsResponse } from '@/types/Column.interface';
import { checkPublic } from '@/utils/shareAccount';

interface ColumnsSectionProps {
dashboardId: string;
Expand All @@ -23,10 +21,8 @@ interface ColumnsSectionProps {
export default function ColumnsSection({ dashboardId }: ColumnsSectionProps) {
const queryClient = useQueryClient();
const { openNewColumnModal, openNotificationModal } = useModal();
const redirectIfNotMember = useRedirectIfNotMember();
const { user } = useSelector((state: RootState) => state.user);
const [isMember, setIsMember] = useState(true);
const [isPublic, setIsPublic] = useState(false);

const {
data: columns,
Expand All @@ -37,31 +33,17 @@ export default function ColumnsSection({ dashboardId }: ColumnsSectionProps) {
const columnList = columns?.data || [];

useEffect(() => {
const handleRedirect = async () => {
const handleCheckMember = async () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

멤버인지 체크하는 원리는, 멤버만 할 수 있는 요청을 보내고 catch에서 실패할 경우 멤버가 아니라고 판단하는 것입니다.
이게 여전히 잘 동작하는 걸로 봐서, Query Cache의 onError는 모든 재요청 후, 실패에 대한 try catch까지 거친 뒤에도 핸들링되지 않은 요청을 받는 것 같습니다.
retry가 있는 경우 리다이렉션이 느려져서 실패한 경우에도 retry하지 않도록 설정했습니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

리트라이는 더블체크용도 였어서 중요한 부분은 아니여서 없어도 괜찮을거 같아요 테스트해보다가 문제가 있다면 그때 다시 추가하면 될거 같습니다

if (!dashboardId) return;
try {
const newIsPublic = await checkPublic(Number(dashboardId));
setIsPublic(newIsPublic);
if (!newIsPublic && dashboardId) {
await getDashboard(String(dashboardId));
}
await instance.get(`/dashboards/${dashboardId}`, {
headers: { memberTest: true },
});
} catch {
redirectIfNotMember();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

리다이렉션 관련 코드 다 지웠습니다!

}
};

const handleCheckMember = async () => {
if (dashboardId) {
try {
await instance.get(`/dashboards/${dashboardId}`, {
headers: { memberTest: true },
});
} catch {
setIsMember(false);
}
setIsMember(false);
}
};

handleRedirect();
handleCheckMember();
}, [dashboardId, user]);

Expand Down Expand Up @@ -106,7 +88,7 @@ export default function ColumnsSection({ dashboardId }: ColumnsSectionProps) {
) : (
<DragDropContext onDragEnd={onDragEnd}>
<section
className={`block h-full overflow-x-auto lg:flex lg:h-[calc(100dvh-70px)] ${isPublic && !user ? 'lg:w-screen' : 'lg:w-[calc(100dvw-300px)]'}`}
className={`block h-full overflow-x-auto lg:flex lg:h-[calc(100dvh-70px)] ${!user ? 'lg:w-screen' : 'lg:w-[calc(100dvw-300px)]'}`}
>
<ul className='block lg:flex'>
{columnList.map((column, index) => (
Expand Down
2 changes: 1 addition & 1 deletion src/containers/dashboard/edit/DashboardModifySection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export default function DashboardModifySection({ initIsPublic, onPublicChange }:
data: dashboard,
isLoading,
error,
} = useFetchData<Dashboard>(['dashboard', id], () => getDashboard(id as string));
} = useFetchData<Dashboard>(['dashboard', id], () => getDashboard(id as string), !!id);

const { data: favoriteList } = useFetchData<FavoriteDashboard[]>(
['favorites', favoriteUserId],
Expand Down
6 changes: 4 additions & 2 deletions src/containers/dashboard/edit/InvitedMembersSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@ export default function InvitedMembersSection() {
const { id } = router.query;
const [currentChunk, setCurrentChunk] = useState(1);

const { data, isLoading, error } = useFetchData<DashboardInvitationsResponse>(['invitations', id, currentChunk], () =>
getDashboardInvitations(Number(id), currentChunk, 5),
const { data, isLoading, error } = useFetchData<DashboardInvitationsResponse>(
['invitations', id, currentChunk],
() => getDashboardInvitations(Number(id), currentChunk, 5),
!!id,
);
const totalPage = data ? Math.max(1, Math.ceil(data.totalCount / 5)) : 1;

Expand Down
6 changes: 4 additions & 2 deletions src/containers/dashboard/edit/MembersSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ export default function MembersSection({ onDeleteMember }: MemberSectionProps) {
const { id } = router.query;
const [currentChunk, setCurrentChunk] = useState(1);

const { data, isLoading, error } = useFetchData<MembersResponse>(['members', id, currentChunk], () =>
getMembersList(Number(id), currentChunk, 4),
const { data, isLoading, error } = useFetchData<MembersResponse>(
['members', id, currentChunk],
() => getMembersList(Number(id), currentChunk, 4),
!!id,
);
const totalPage = data ? Math.max(1, Math.ceil(data.totalCount / 4)) : 1;

Expand Down
23 changes: 2 additions & 21 deletions src/containers/dashboard/edit/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,17 @@ import InvitedMembersSection from './InvitedMembersSection';
import MembersSection from './MembersSection';

import useDeleteData from '@/hooks/useDeleteData';
import useFetchData from '@/hooks/useFetchData';
import useModal from '@/hooks/useModal';
import useRedirectIfNoPermission from '@/hooks/useRedirectIfNoPermission';
import { deleteDashboard } from '@/services/deleteService';
import { getDashboard } from '@/services/getService';
import { Dashboard } from '@/types/Dashboard.interface';
import { DeleteDashboardInput } from '@/types/delete/DeleteDashboardInput.interface';
import { checkPublic } from '@/utils/shareAccount';

export default function DashboardEdit() {
const redirectIfNoPermission = useRedirectIfNoPermission();
const { openConfirmModal } = useModal();
const queryClient = useQueryClient();
const router = useRouter();
const { id } = router.query;

// NOTE: Redirection
const { data: dashboard, error } = useFetchData<Dashboard>(['dashboard', id], () => getDashboard(id as string));

useEffect(() => {
if (dashboard) {
redirectIfNoPermission(dashboard.userId);
} else if (error) {
redirectIfNoPermission(-1);
}
}, [dashboard, error]);

// NOTE: 공유 대시보드 여부 확인
const [isPublic, setIsPublic] = useState(false);

Expand All @@ -51,12 +35,9 @@ export default function DashboardEdit() {

useEffect(() => {
const handleInitIsPublic = async () => {
try {
setIsPublic(await checkPublic(Number(id)));
} catch {
redirectIfNoPermission(-1);
}
setIsPublic(await checkPublic(Number(id)));
};

if (id) handleInitIsPublic();
}, [id]);

Expand Down
7 changes: 5 additions & 2 deletions src/hooks/useDeleteData.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { MutationFunction, useMutation } from '@tanstack/react-query';
import { AxiosError } from 'axios';

import useModal from './useModal';

interface UseDeleteProps<T> {
mutationFn: MutationFunction<unknown, T>;
handleSuccess?: () => void;
Expand All @@ -9,6 +11,7 @@ interface UseDeleteProps<T> {

// NOTE: 삭제 요청을 돕는 훅
const useDeleteData = <T>({ mutationFn, handleSuccess, handleError }: UseDeleteProps<T>) => {
const { openNotificationModal } = useModal();
return useMutation<unknown, unknown, T, unknown>({
mutationFn,
onSuccess: () => {
Expand All @@ -24,9 +27,9 @@ const useDeleteData = <T>({ mutationFn, handleSuccess, handleError }: UseDeleteP
} else {
// NOTE: 에러 처리는 일관되게 서버 메세지 있는 경우 보여주고, 아니면 로그 출력하도록 했습니다.
if (error instanceof AxiosError) {
alert(error.response?.data.message);
openNotificationModal({ text: error.response?.data.message });
} else {
alert('실패했습니다.');
openNotificationModal({ text: '실패했습니다.' });
console.log(error);
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/hooks/useFetchData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@ const useFetchData = <T>(
const response = await getService();
return response.data;
} catch (error) {
throw new Error('데이터를 불러오는 중 에러 발생: ' + error);
throw error;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

원본 에러 보내주도록 했습니다.

}
},
retry: 1, // NOTE: 요청 실패시 1회까지만 재시도하도록 제한
refetchInterval: refetchInterval, // NOTE: 주기적인 초대내역 수신을 위해 설정
enabled: enabled,
refetchInterval: refetchInterval,
refetchInterval: refetchInterval, // NOTE: 주기적인 초대내역 수신을 위해 설정
});
};

Expand Down
25 changes: 25 additions & 0 deletions src/hooks/useRedirect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

import useModal from '@/hooks/useModal';

const useRedirect = () => {
const { openNotificationModal } = useModal();
const router = useRouter();
const { id } = router.query;
const [initialCheck, setInitialCheck] = useState(true);

useEffect(() => {
setInitialCheck(true);
}, [router.pathname, id]);

return (path: string, text: string) => {
if (initialCheck) {
openNotificationModal({ text });
router.replace(path);
setInitialCheck(false);
}
};
};

export default useRedirect;
30 changes: 0 additions & 30 deletions src/hooks/useRedirectIfAuth.ts

This file was deleted.

Loading