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

⚙️ Chore: Tanstack Query 업그레이드 #96

Merged
merged 5 commits into from
Jun 26, 2024
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
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);
Copy link
Contributor

Choose a reason for hiding this comment

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

원래 useFetchData랑 똑같이 사용하면 되나요???
const { data, isLoading, error } = useFetchData...
에러 핸들링 처리를 useQuery 가 해주는 건가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

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

넵 뭐 바꿀필요 없이 원래 쓰시던 대로 쓰시면 됩니다!
내부 로직만 바뀌었고, 파라미터나 리턴값으로 리스폰스 데이터 주는 것은 똑같아요!

}
},
});
};
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} />
Copy link
Contributor Author

Choose a reason for hiding this comment

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

개발 모드에서 리액트 쿼리 개발자 툴을 보실 수 있습니다!

Copy link
Contributor

Choose a reason for hiding this comment

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

개발 모드는 run dev 했을때인가요??

Copy link
Contributor Author

Choose a reason for hiding this comment

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

네 맞습니다! pnpm run dev 후 개발 모드에서만 툴이 뜨고, 배포된 프로덕션에는 뜨지 않아요!

</QueryClientProvider>
</PersistGate>
</Provider>
Expand Down