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

[Feat] 툴 북마크 상태 반영 #165

Merged
merged 1 commit into from
Jan 24, 2025
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
12 changes: 3 additions & 9 deletions src/apis/tool/queries.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
import { get } from '@apis/index';
import { MYPAGE_QUERY_KEY } from '@pages/myPage/apis/queries';
import { ToolList } from '@pages/myPage/types/tool';
import { DETAIL_QUERY_KEY } from '@pages/toolDetail/apis/api';
import { ToolType } from '@pages/toolDetail/types';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import type { AxiosResponse } from 'axios';
import { useState } from 'react';

import { postToolScrap } from './api';
import { DETAIL_QUERY_KEY } from './getToolData';

export const useToolScrap = () => {
const userItem = localStorage.getItem('user');
const userData = userItem ? JSON.parse(userItem) : null;
const userId = userData?.accessToken || null;
const [toolId, setToolId] = useState<number | null>(null);

const queryClient = useQueryClient();
return useMutation({
mutationFn: (toolId: number) => postToolScrap(toolId),
onMutate: async (toolId: number) => {
setToolId(toolId);
// 캐시 백업
const previousBoardList = queryClient.getQueryData(MYPAGE_QUERY_KEY.MY_FAVORITE_TOOL_LIST(userId));

Expand All @@ -41,13 +38,10 @@ export const useToolScrap = () => {
queryClient.setQueryData(MYPAGE_QUERY_KEY.MY_FAVORITE_TOOL_LIST(userId), context.previousBoardList);
}
},
onSettled: () => {
onSettled: (_, __, toolId) => {
// 서버 동기화를 위해 캐시 무효화
// TODO: 민이가 작업하는 툴 리스트 페이지, 찬영언니가 작업하는 툴 디테일 페이지의 쿼리키도 무효화해주기
queryClient.refetchQueries({ queryKey: MYPAGE_QUERY_KEY.MY_FAVORITE_TOOL_LIST(userId) });
if (toolId) {
queryClient.refetchQueries({ queryKey: DETAIL_QUERY_KEY.SCRAPPED_TOOLS(toolId) });
}
queryClient.refetchQueries({ queryKey: DETAIL_QUERY_KEY.TOOL_DETAIL(toolId) });
},
});
};
Expand Down
23 changes: 10 additions & 13 deletions src/pages/toolDetail/ToolDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Spacing from '@components/spacing/Spacing';
import Title from '@components/title/Title';
import NotFound from '@pages/error/NotFound';
import { useRef } from 'react';
import { useNavigate, useParams } from 'react-router-dom'; // useParams 가져오기
import { useNavigate, useParams } from 'react-router-dom';

import BreadCrumb from './components/breadcrumb/BreadCrumb';
import ToolCommunity from './components/community/Community';
Expand All @@ -16,15 +16,14 @@ import ToolIntro from './components/toolIntro/ToolIntro';
import * as S from './ToolDetail.styled';

const ToolDetail = () => {
const { toolId } = useParams(); // URL에서 toolId 가져오기
const { toolId } = useParams<{ toolId: string }>(); // useParams 타입 명시
const ToolIntroRef = useRef<HTMLDivElement>(null);
const CoreFeatureRef = useRef<HTMLDivElement>(null);
const ReferenceVideoRef = useRef<HTMLDivElement>(null);
const PlanBoxRef = useRef<HTMLDivElement>(null);
const ToolCommunityRef = useRef<HTMLDivElement>(null);
const navigate = useNavigate();

// toolId를 숫자로 변환하여 전달
const numericToolId = Number(toolId);
const { data, isError } = useToolData(numericToolId);

Expand Down Expand Up @@ -55,12 +54,12 @@ const ToolDetail = () => {
<>
<Title title={data.toolMainName} tool={data.toolMainName} />
<S.ToolDetailWrapper>
<Spacing size={'1.8'} />
<Spacing size="1.8" />
<BreadCrumb activeTopic={data.category} activeTool={data.toolMainName} />
<Spacing size={'1.8'} />
<Spacing size="1.8" />
<ToolInfoCard toolData={data} />

<Spacing size={'1'} />
<Spacing size="1" />

<S.ToolDetailContainer>
<section>
Expand All @@ -75,24 +74,22 @@ const ToolDetail = () => {
<ReferenceVideo ref={ReferenceVideoRef} toolId={numericToolId} alternate={data.toolLogo} />
<PlanBox ref={PlanBoxRef} toolId={numericToolId} />

<Spacing size={'1'} />
<Spacing size="1" />
</S.ToolDetailBox>
<Spacing size={'1'} />
<Spacing size="1" />

<S.ToolCommunityBox>
<S.ToolCommunityBox>
<ToolCommunity toolId={numericToolId} ref={ToolCommunityRef} boardId={0} onClick={goCommunity} />
</S.ToolCommunityBox>
<ToolCommunity toolId={numericToolId} ref={ToolCommunityRef} boardId={0} onClick={goCommunity} />
</S.ToolCommunityBox>
<Spacing size={'7.2'} />
<Spacing size="7.2" />
</section>
<Sidewing sectionRefs={sectionRefs} toolId={numericToolId} />
</S.ToolDetailContainer>
</S.ToolDetailWrapper>
</>
);
}
// 데이터가 로드되지 않은 경우 null 반환

return null;
};

Expand Down
1 change: 0 additions & 1 deletion src/pages/toolDetail/apis/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export const DETAIL_QUERY_KEY = {
CORE_FEATURES: (coreID: number) => ['corefeature', coreID],
TOOL_PLAN: (planID: number) => ['toolplan', planID],
RELATED_TOOLS: (toolID: number) => ['relatedtool', toolID],
SCRAPPED_TOOLS: (toolId: number) => ['scrappedtool', toolId],
};

// 핵심 기능 조회하기
Expand Down
11 changes: 4 additions & 7 deletions src/pages/toolDetail/components/toolInfoCard/ToolInfoCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,12 @@ const ToolInfoCard = ({ toolData }: ToolInfoCardPropTypes) => {
} = toolData;

const [isClickBtn, setIsClickBtn] = useState(false);
const [isBookmark, setIsBookmark] = useState(isScrapped);
const [toastMessage, setToastMessage] = useState<string | null>(null);
const [isToastWarning, setIsToastWarning] = useState(false);

const { handleModalOpen, isToastOpen } = useToastOpen(); // useToastOpen 훅 사용

const toolScrapMutation = useToolScrap();
const { mutateAsync } = useToolScrap();

const darudaToolLink = useLocation();
const baseURL = import.meta.env.VITE_CLIENT_URL;
Expand Down Expand Up @@ -79,10 +78,9 @@ const ToolInfoCard = ({ toolData }: ToolInfoCardPropTypes) => {
return;
}

setIsBookmark((prev) => !prev);
try {
await toolScrapMutation.mutateAsync(toolId);
if (isBookmark) {
await mutateAsync(toolId);
if (isScrapped) {
setToastMessage('북마크가 취소되었어요');
} else {
setToastMessage('북마크가 추가되었어요');
Expand All @@ -91,7 +89,6 @@ const ToolInfoCard = ({ toolData }: ToolInfoCardPropTypes) => {
handleModalOpen();
} catch (error) {
console.error('북마크 업데이트 실패:', error);
setIsBookmark((prev) => !prev);
setIsToastWarning(true);
setToastMessage('북마크 업데이트 실패');
handleModalOpen();
Expand Down Expand Up @@ -120,7 +117,7 @@ const ToolInfoCard = ({ toolData }: ToolInfoCardPropTypes) => {
<IcArrowRightupWhite24 />
직접 체험해보기
</S.GoSiteBtn>
<S.BookmarkIconBox $isBookmark={isBookmark} onClick={() => handleBookmark()}>
<S.BookmarkIconBox $isBookmark={isScrapped} onClick={() => handleBookmark()}>
<IcBookmarkIris121Default />
</S.BookmarkIconBox>
<S.ShareIconBox onClick={() => handleCopyClipBoard(`${baseURL}${darudaToolLink.pathname}`)}>
Expand Down
Loading