Skip to content

Commit

Permalink
refactor: useSuspenseQuery 적용 및 훅 리팩터링 (#326)
Browse files Browse the repository at this point in the history
* chore: 확장자 tsx -> ts로 변경

* chore: Spinner 삭제

* chore: useReminderHooks, useCalendar 사용처로 폴더 이동

* build: react-query를 5.0.0-beta로 업데이트

* refactor: useSuspenseQuery 마이그레이션

* chore: 사용하지 않는 import 삭제

* chore: useDictionaryPlantDetail 네이밍 변경 적용

* chore: type import 추가

* refactor: 재사용되는 Skeleton 컴포넌트 추출

* fix: Spinner 대신 Loading 페이지로 변경

* refactor: query 커스텀 훅 변경내용 적용

* chore: useCheckSessionId 사용 안함

* build: package.json @tanstack/react-query: 5.0.0-beta.20 적용

* chore: 절대경로로 변경

* chore: hooks 폴더 안으로 이동

* style: 변수 구조분해 할당

* chore: 수정 함수를 그대로 사용

* refactor: refetch 대신 invalidateQueries 사용

* fix: history 모의 API 에도 세션 검층 추가
  • Loading branch information
bassyu authored and Choi-JJunho committed Sep 20, 2023
1 parent 8696c7a commit c22cdc6
Show file tree
Hide file tree
Showing 30 changed files with 253 additions and 334 deletions.
195 changes: 125 additions & 70 deletions frontend/package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"license": "MIT",
"dependencies": {
"@tanstack/react-query": "^5.0.0-alpha.86",
"@tanstack/react-query": "^5.0.0-beta.20",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.14.1",
Expand Down Expand Up @@ -46,7 +46,7 @@
"@typescript-eslint/parser": "^5.61.0",
"copy-webpack-plugin": "^11.0.0",
"cross-env": "^7.0.3",
"cypress": "^12.17.2",
"cypress": "^13.1.0",
"dotenv-webpack": "^8.0.1",
"eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0",
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion frontend/src/components/@common/Calendar/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { useState } from 'react';
import { AlertSpan, Button, CalendarBox, DaysBox, HeaderBox, Wrapper } from './Calendar.style';
import useCalendar from 'hooks/useCalendar';
import { convertDateKorYear, getDateToString, getDayInfo, getDaysBetween } from 'utils/date';
import { DateValidate } from 'utils/validate';
import { DAYS_OF_THE_WEEK } from 'constants/index';
import ArrowLeft from '../Icons/ArrowLeft';
import ArrowRight from '../Icons/ArrowRight';
import DaySmallBox from './DaySmallBox';
import useCalendar from './hooks/useCalendar';

interface CalendarProps {
selectedDate: Date | null;
Expand Down
23 changes: 0 additions & 23 deletions frontend/src/components/@common/Spinner/Spinner.stories.tsx

This file was deleted.

30 changes: 0 additions & 30 deletions frontend/src/components/@common/Spinner/Spinner.style.ts

This file was deleted.

26 changes: 0 additions & 26 deletions frontend/src/components/@common/Spinner/index.tsx

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react';
import { Suspense } from 'react';
import LoadingSpinner from 'components/@common/Spinner';
import Loading from 'pages/Loading';
import PetDetails from '.';

const meta: Meta<typeof PetDetails> = {
Expand All @@ -12,7 +12,7 @@ const meta: Meta<typeof PetDetails> = {

decorators: [
(Story) => (
<Suspense fallback={<LoadingSpinner />}>
<Suspense fallback={<Loading />}>
<Story />
</Suspense>
),
Expand Down
32 changes: 32 additions & 0 deletions frontend/src/components/petPlant/Timeline/Skeleton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import {
DayArea,
DayHeader,
SkeletonItem,
SkeletonItemContent,
TimelineArea,
YearHeader,
} from './Timeline.style';

interface SkeletonProps {
hasYearHeader?: boolean;
}

const Skeleton = ({ hasYearHeader }: SkeletonProps) => (
<>
{hasYearHeader && <YearHeader />}
{Array(10)
.fill(null)
.map((_, index) => (
<DayArea key={index}>
<DayHeader />
<TimelineArea>
<SkeletonItem>
<SkeletonItemContent />
</SkeletonItem>
</TimelineArea>
</DayArea>
))}
</>
);

export default Skeleton;
29 changes: 7 additions & 22 deletions frontend/src/components/petPlant/Timeline/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import {
Plant,
PlantImage,
Sensor,
SkeletonItem,
SkeletonItemContent,
Spot,
TimelineArea,
Wrapper,
Expand All @@ -23,6 +21,7 @@ import useYearList from 'hooks/queries/history/useYearList';
import useIntersectionRef from 'hooks/useIntersectionRef';
import Sprout from 'assets/sprout.svg';
import TimelineItemList from '../TimelineItemList';
import Skeleton from './Skeleton';

interface TimelineProps {
petPlantId: PetPlantDetails['id'];
Expand All @@ -32,8 +31,8 @@ interface TimelineProps {
const Timeline = ({ petPlantId, filter }: TimelineProps) => {
const {
data: yearList,
isSuccess,
hasNextPage,
isLoading,
isFetchingNextPage,
fetchNextPage,
} = useYearList(Number(petPlantId), filter);
Expand All @@ -48,7 +47,7 @@ const Timeline = ({ petPlantId, filter }: TimelineProps) => {
<Plant>
<PlantImage src={Sprout} alt="타임라인 꼭대기" />
</Plant>
{yearList &&
{isSuccess ? (
yearList.map(([year, monthList]) => (
<YearArea key={year}>
<YearHeader>{year}</YearHeader>
Expand All @@ -70,26 +69,12 @@ const Timeline = ({ petPlantId, filter }: TimelineProps) => {
</MonthArea>
))}
</YearArea>
))}
{(isLoading || isFetchingNextPage) && (
<>
{isLoading && <YearHeader />}
{Array(10)
.fill(null)
.map((_, index) => (
<DayArea key={index}>
<DayHeader />
<TimelineArea>
<SkeletonItem>
<SkeletonItemContent />
</SkeletonItem>
</TimelineArea>
</DayArea>
))}
</>
))
) : (
<Skeleton hasYearHeader />
)}
{isFetchingNextPage ? <Skeleton /> : <Sensor ref={intersectionRef} />}
{!hasNextPage && <Earth />}
{!isFetchingNextPage && <Sensor ref={intersectionRef} />}
</Wrapper>
);
};
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/reminder/MonthBox/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ReminderExtendType } from 'types/reminder';
import type { ReminderExtendType } from 'types/reminder';
import { MonthReminderBox, MonthTitle } from './MonthBox.style';
import CardBox from '../CardBox';

Expand Down
7 changes: 3 additions & 4 deletions frontend/src/hooks/queries/auth/useCheckSessionId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ import AuthAPI from 'apis/auth';
import noRetryIfUnauthorized from 'utils/noRetryIfUnauthorized';
import throwOnInvalidStatus from 'utils/throwOnInvalidStatus';

const useCheckSessionId = (suspense = true) => {
return useQuery<null, Error | StatusError>({
const useCheckSessionId = (throwOnError = true) =>
useQuery<null, Error | StatusError>({
queryKey: ['checkSessionId'],
queryFn: async () => {
const response = await AuthAPI.checkSessionId();
throwOnInvalidStatus(response);
return null;
},

throwOnError,
retry: noRetryIfUnauthorized,
suspense,
});
};

export default useCheckSessionId;
10 changes: 3 additions & 7 deletions frontend/src/hooks/queries/auth/useLogin.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import { useQuery } from '@tanstack/react-query';
import { useSuspenseQuery } from '@tanstack/react-query';
import AuthAPI from 'apis/auth';
import throwOnInvalidStatus from 'utils/throwOnInvalidStatus';

const useLogin = (code: string) => {
return useQuery<null, Error, void>({
const useLogin = (code: string) =>
useSuspenseQuery<null, Error, void>({
queryKey: ['getSession', code],
queryFn: async () => {
const response = await AuthAPI.getSessionId(code);

throwOnInvalidStatus(response);

return null;
},
suspense: true,
});
};

export default useLogin;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { DictionaryPlant, Season, SeasonKor } from 'types/dictionaryPlant';
import { useQuery } from '@tanstack/react-query';
import { useSuspenseQuery } from '@tanstack/react-query';
import DictionaryPlantAPI, { DICTIONARY_PLANT_URL } from 'apis/dictionaryPlant';
import { SEASONS } from 'constants/index';

Expand All @@ -15,7 +15,7 @@ const initialWaterOptions: DictionaryPlantExtendCycles['waterOptions'] = {
};

const useDictionaryPlantDetail = (id: number) =>
useQuery<DictionaryPlant, Error, DictionaryPlantExtendCycles>({
useSuspenseQuery<DictionaryPlant, Error, DictionaryPlantExtendCycles>({
queryKey: [DICTIONARY_PLANT_URL, 'detail', id],

queryFn: async () => {
Expand All @@ -27,8 +27,6 @@ const useDictionaryPlantDetail = (id: number) =>
},

staleTime: Infinity,
suspense: true,
throwOnError: true,
select: (data) => {
const { waterCycle } = data;

Expand Down
12 changes: 4 additions & 8 deletions frontend/src/hooks/queries/history/useYearList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,9 @@ import {
import HistoryAPI, { HISTORY_URL } from 'apis/history';
import noRetryIfUnauthorized from 'utils/noRetryIfUnauthorized';
import throwOnInvalidStatus from 'utils/throwOnInvalidStatus';
import useCheckSessionId from '../auth/useCheckSessionId';

const useYearList = (petPlantId: PetPlantDetails['id'], filter: HistoryType[] = []) => {
const { isSuccess } = useCheckSessionId();

return useInfiniteQuery<
const useYearList = (petPlantId: PetPlantDetails['id'], filter: HistoryType[] = []) =>
useInfiniteQuery<
HistoryResponse,
Error,
YearList,
Expand All @@ -32,7 +29,7 @@ const useYearList = (petPlantId: PetPlantDetails['id'], filter: HistoryType[] =
return data;
},

defaultPageParam: 0,
initialPageParam: 0,
getNextPageParam: ({ hasNext }, _allPages, lastPageParam) => {
return hasNext ? lastPageParam + 1 : undefined;
},
Expand All @@ -44,12 +41,11 @@ const useYearList = (petPlantId: PetPlantDetails['id'], filter: HistoryType[] =
return yearList;
},

throwOnError: true,
retry: noRetryIfUnauthorized,
enabled: isSuccess,
refetchOnWindowFocus: false,
placeholderData: keepPreviousData,
gcTime: 0,
});
};

export default useYearList;
10 changes: 2 additions & 8 deletions frontend/src/hooks/queries/petPlant/usePetPlantCardList.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import type { DataResponse } from 'types/DataResponse';
import type { PetPlantItem } from 'types/petPlant';
import { useQuery } from '@tanstack/react-query';
import { useSuspenseQuery } from '@tanstack/react-query';
import PetPlantAPI, { PET_PLANT_URL } from 'apis/petPlant';
import noRetryIfUnauthorized from 'utils/noRetryIfUnauthorized';
import throwOnInvalidStatus from 'utils/throwOnInvalidStatus';
import useCheckSessionId from '../auth/useCheckSessionId';

const usePetPlantCardList = () => {
const { isSuccess } = useCheckSessionId();

return useQuery<DataResponse<PetPlantItem[]>, Error, PetPlantItem[]>({
return useSuspenseQuery<DataResponse<PetPlantItem[]>, Error, PetPlantItem[]>({
queryKey: [PET_PLANT_URL, 'list'],
queryFn: async () => {
const response = await PetPlantAPI.getList();
Expand All @@ -20,10 +17,7 @@ const usePetPlantCardList = () => {
},

select: ({ data }) => data,

suspense: true,
retry: noRetryIfUnauthorized,
enabled: isSuccess,
});
};

Expand Down
Loading

0 comments on commit c22cdc6

Please sign in to comment.