Skip to content

Commit

Permalink
[FE] Refactor/#645: Home 페이지 API 로직 수정 및 React-Query 적용 (#646)
Browse files Browse the repository at this point in the history
* feat : Add HTTP client module

* feat : Add QueryClient and QueryClientProvider for React Query

* feat : Add API and hook for fetching topics

* refactor : Refactor authorization header in http.ts

* feat : Add useTopicsQuery hook to TopicCardContainer

* refactor : Refactor TopicCard and TopicCardContainer components

eliminate useState,useEffect in TopicCardContainer
  • Loading branch information
jiwonh423 authored Feb 5, 2024
1 parent d77d381 commit f67141a
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 23 deletions.
35 changes: 35 additions & 0 deletions frontend/src/api/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';

const API_POSTFIX = 'api';
const BASE_URL = process.env.APP_URL || `https://mapbefine.com/${API_POSTFIX}`;

const token = localStorage.getItem('userToken');

const axiosInstance = axios.create({
baseURL: BASE_URL,
headers: token ? { Authorization: `Bearer ${token}` } : {},
});

export interface HttpClient extends AxiosInstance {
get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T>;
post<T = unknown>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<T>;
patch<T = unknown>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<T>;
put<T = unknown>(
url: string,
data?: any,
config?: AxiosRequestConfig,
): Promise<T>;
delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T>;
}

export const http: HttpClient = axiosInstance;

http.interceptors.response.use((res) => res.data);
4 changes: 4 additions & 0 deletions frontend/src/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { TopicCardProps } from '../types/Topic';
import { http } from './http';

export const getTopics = (url: string) => http.get<TopicCardProps[]>(url);
8 changes: 5 additions & 3 deletions frontend/src/components/TopicCard/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SyntheticEvent, useContext, useState } from 'react';
import { QueryObserverResult, RefetchOptions } from '@tanstack/react-query';
import { useContext, useState } from 'react';
import { styled } from 'styled-components';

import SeeTogetherSVG from '../../assets/seeTogetherBtn_filled.svg';
Expand Down Expand Up @@ -26,7 +27,9 @@ interface OnClickDesignatedProps {
interface TopicCardExtendedProps extends TopicCardProps {
cardType: 'default' | 'modal';
onClickDesignated?: ({ topicId, topicName }: OnClickDesignatedProps) => void;
getTopicsFromServer?: () => void;
getTopicsFromServer?: (
options?: RefetchOptions | undefined,
) => Promise<QueryObserverResult<TopicCardProps[], Error>>;
}

function TopicCard({
Expand All @@ -39,7 +42,6 @@ function TopicCard({
pinCount,
bookmarkCount,
isInAtlas,
isBookmarked,
onClickDesignated,
getTopicsFromServer,
}: TopicCardExtendedProps) {
Expand Down
23 changes: 3 additions & 20 deletions frontend/src/components/TopicCardContainer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { Swiper, Tab } from 'map-befine-swiper';
import { useEffect, useState } from 'react';
import { styled } from 'styled-components';

import useGet from '../../apiHooks/useGet';
import useTopicsQuery from '../../hooks/api/useTopicsQuery';
import useKeyDown from '../../hooks/useKeyDown';
import { TopicCardProps } from '../../types/Topic';
import Box from '../common/Box';
import Flex from '../common/Flex';
import Space from '../common/Space';
Expand All @@ -25,23 +23,8 @@ function TopicCardContainer({
containerDescription,
routeWhenSeeAll,
}: TopicCardContainerProps) {
const [topics, setTopics] = useState<TopicCardProps[] | null>(null);
const { topics, refetchTopics } = useTopicsQuery(url);
const { elementRef, onElementKeyDown } = useKeyDown<HTMLSpanElement>();
const { fetchGet } = useGet();

const setTopicsFromServer = async () => {
await fetchGet<TopicCardProps[]>(
url,
'지도를 가져오는데 실패했습니다. 잠시 후 다시 시도해주세요.',
(response) => {
setTopics(response);
},
);
};

useEffect(() => {
setTopicsFromServer();
}, []);

return (
<section>
Expand Down Expand Up @@ -112,7 +95,7 @@ function TopicCardContainer({
bookmarkCount={topic.bookmarkCount}
isInAtlas={topic.isInAtlas}
isBookmarked={topic.isBookmarked}
getTopicsFromServer={setTopicsFromServer}
getTopicsFromServer={refetchTopics}
/>
<CustomSpace />
</Flex>
Expand Down
13 changes: 13 additions & 0 deletions frontend/src/hooks/api/useTopicsQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useQuery } from '@tanstack/react-query';

import { getTopics } from '../../api';

const useTopicsQuery = (url: string) => {
const { data: topics, refetch: refetchTopics } = useQuery({
queryKey: ['topics', url],
queryFn: () => getTopics(url),
});
return { topics, refetchTopics };
};

export default useTopicsQuery;
2 changes: 2 additions & 0 deletions frontend/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ if (process.env.REACT_APP_GOOGLE_ANALYTICS) {
ReactGA.initialize(process.env.REACT_APP_GOOGLE_ANALYTICS);
}

const queryClient = new QueryClient();

root.render(
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={theme}>
Expand Down

0 comments on commit f67141a

Please sign in to comment.