Skip to content

Commit

Permalink
⚙️ Chore: Tanstack Query 업그레이드 (#96)
Browse files Browse the repository at this point in the history
* ⚙  chore(#73): install Tanstack Query

* 🛠  fix(#73): tanstack query 패키지 임포트 & 개발자 도구 추가

* 🛠  fix(#73): useFetchData 수정 - Tanstack Query 적용

* 🛠  fix(#73): useSignIn 수정 - Tanstack Query 적용

* 🛠  fix(#73): useFetchDashboards 수정 - Tanstack Query 적용
  • Loading branch information
wayandway authored Jun 26, 2024
1 parent e1dfd3b commit f22a90f
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 37 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
"dependencies": {
"@hookform/resolvers": "^3.6.0",
"@reduxjs/toolkit": "^2.2.5",
"@tanstack/react-query": "^5.48.0",
"@tanstack/react-query-devtools": "^5.48.0",
"axios": "^1.7.2",
"next": "14.2.4",
"react": "^18",
Expand Down
38 changes: 38 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 19 additions & 15 deletions src/hooks/useFetchDashboards.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
import { useQuery } from 'react-query';
import { useDispatch, useSelector } from 'react-redux';
import { useQuery } from '@tanstack/react-query';
import { useDispatch } from 'react-redux';

import { getDashboardsList } from '@/services/getService';
import { setDashboards } from '@/store/reducers/dashboardsSlice';

const fetchDashboards = async () => {
const response = await getDashboardsList();

if (response.status !== 200) {
throw new Error('Failed to fetch dashboards');
}

return response.data;
};

export const useFetchDashboards = () => {
const dispatch = useDispatch();

return useQuery('dashboards', () => fetchDashboards(), {
onSuccess: (data) => {
dispatch(setDashboards({ dashboards: data.dashboards, totalCount: data.totalCount }));
const { isLoading, error, data, isFetching } = useQuery({
queryKey: ['dashboards'], // 쿼리 키는 문자열이나 배열로 지정할 수 있습니다
queryFn: async () => {
try {
const response = await getDashboardsList();
if (response.status !== 200) {
throw new Error('Failed to fetch dashboards');
}
const data = response.data;
dispatch(setDashboards({ dashboards: data.dashboards, totalCount: data.totalCount }));
return data; // 데이터를 반환해야 합니다
} catch (error) {
// 에러 처리
throw new Error('데이터를 불러오는 중 에러 발생: ' + error);
}
},
});

return { isLoading, error, data, isFetching };
};
22 changes: 11 additions & 11 deletions src/hooks/useFetchData.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { useQuery, QueryKey } from 'react-query';

const useFetchData = <T>(queryKey: QueryKey, getService: () => Promise<{ data: T }>) => {
const fetchData = async () => {
const response = await getService();
return response.data;
};
import { useQuery, QueryKey, UseQueryResult } from '@tanstack/react-query';

const useFetchData = <T>(queryKey: QueryKey, getService: () => Promise<{ data: T }>): UseQueryResult<T, Error> => {
return useQuery<T, Error>({
queryKey, // 캐시 키를 임의로 지정할 수 있음
queryFn: fetchData, // 비동기 getService 함수 (services/ 에 정의)
onError: (error: Error) => {
console.error('Error fetching data:', error);
queryKey: queryKey,
queryFn: async () => {
try {
const response = await getService();
return response.data;
} catch (error) {
// 에러 처리
throw new Error('데이터를 불러오는 중 에러 발생: ' + error);
}
},
});
};
Expand Down
23 changes: 13 additions & 10 deletions src/hooks/useSignIn.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMutation } from 'react-query';
import { useMutation } from '@tanstack/react-query';
import { useDispatch } from 'react-redux';

import { postSignIn } from '@/services/postService';
Expand All @@ -8,15 +8,8 @@ import { SignInForm, SignInResponse } from '@/types/post/SignInForm.interface';
export const useSignIn = () => {
const dispatch = useDispatch();

return useMutation<SignInResponse, unknown, SignInForm>(postSignIn, {
onMutate: () => {
dispatch(isLoading(true));
dispatch(setError(null));
},
onSuccess: (data) => {
dispatch(setUser(data));
dispatch(isLoading(false));
},
return useMutation<SignInResponse, unknown, SignInForm, unknown>({
mutationFn: postSignIn,
onError: (error: unknown) => {
if (error instanceof Error) {
dispatch(setError(error.message));
Expand All @@ -25,5 +18,15 @@ export const useSignIn = () => {
}
dispatch(isLoading(false));
},
onSuccess: (data) => {
dispatch(setUser(data));
dispatch(isLoading(false));
},
onMutate: async () => {
dispatch(isLoading(true));
dispatch(setError(null));
// 이 부분에서 필요한 경우 이전 상태를 저장하거나 다른 작업을 수행할 수 있음
return null; // 반환 값은 나중에 revert 함수에서 사용할 수 있음
},
});
};
4 changes: 3 additions & 1 deletion src/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import '@/styles/globals.css';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import type { AppProps } from 'next/app';
import { QueryClient, QueryClientProvider } from 'react-query';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';

Expand All @@ -17,6 +18,7 @@ export default function App({ Component, pageProps }: AppProps) {
<MainLayout>
<Component {...pageProps} />
</MainLayout>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</PersistGate>
</Provider>
Expand Down

0 comments on commit f22a90f

Please sign in to comment.