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

MARA-65 에러바운더리, fallback #17

Merged
merged 21 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
1 change: 1 addition & 0 deletions .github/workflows/workflow-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ jobs:
# 환경 변수 추가
- name: Set Environment Variables
run: |
echo "NEXT_PUBLIC_BASE_URI=${{ secrets.NEXT_PUBLIC_BASE_URI }}" >> .env
echo "NEXT_PUBLIC_KAKAO_API_KEY=${{ secrets.NEXT_PUBLIC_KAKAO_API_KEY }}" >> .env
echo "NEXT_PUBLIC_KAKAO_REDIRECT_URI=${{ secrets.NEXT_PUBLIC_KAKAO_REDIRECT_URI }}" >> .env
echo "NEXT_PUBLIC_GOOGLE_API_KEY=${{ secrets.NEXT_PUBLIC_GOOGLE_API_KEY }}" >> .env
Expand Down
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"next": "14.0.3",
"react": "^18",
"react-dom": "^18",
"react-error-boundary": "^4.0.12",
"recoil": "^0.7.7"
},
"devDependencies": {
Expand Down
2 changes: 1 addition & 1 deletion src/api/axiosInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export interface ApiResponseDTO<T> {
}

const axiosInstance = axios.create({
baseURL: 'https://localhost:3000',
baseURL: process.env.NEXT_PUBLIC_BASE_URI,
timeout: 5000,
headers: {
'Content-Type': 'application/json',
Expand Down
31 changes: 0 additions & 31 deletions src/api/login/getToken.ts

This file was deleted.

Binary file added src/assets/lottie.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions src/components/templates/ErrorFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import React from 'react';
import { Button } from '../atoms';

const ErrorFallback: React.FC = ({
resetErrorBoundary,
}: {
resetErrorBoundary?: () => void;
}) => {
const handleRefresh = () => {
if (resetErrorBoundary) {
resetErrorBoundary();
}
};
return (
<div className="flex justify-center items-center bg-gray2">
<div className="flex flex-col w-[100vw] max-w-[480px] min-h-[100vh] bg-white">
<section
className={`flex flex-col justify-center gap-[50px] p-[20px] flex-1`}
>
<div className="text-center">에러 발생!</div>
<Button
className="bg-primary2 text-white"
text={'다시 요청하기'}
onClick={handleRefresh}
/>
</section>
</div>
</div>
);
};

export default ErrorFallback;
15 changes: 15 additions & 0 deletions src/components/templates/SuspenseFallback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import Image from 'next/image';
import React from 'react';
import LottieGif from '@/assets/lottie.gif';

const SuspenseFallback: React.FC = () => {
return (
<div className="flex justify-center items-center bg-gray2">
<div className="flex justify-center items-center w-[100vw] max-w-[480px] min-h-[100vh] bg-white">
<Image src={LottieGif} alt="로딩중" />
</div>
</div>
);
};

export default SuspenseFallback;
2 changes: 2 additions & 0 deletions src/components/templates/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export { default as Layout } from './Layout';
export { default as FriendListTemplate } from './FriendListTemplate';
export { default as AddFriendTemplate } from './AddFriendTemplate';
export { default as ErrorFallback } from './ErrorFallback';
export { default as SuspenseFallback } from './SuspenseFallback';
4 changes: 3 additions & 1 deletion src/components/templates/withLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import React, { useEffect } from 'react';
import { useRouter } from 'next/router';
import useToast from '@/hooks/useToast';

const withLogin = (InnerComponent: React.FC) => {
return () => {
const router = useRouter();
const token = localStorage.getItem('token');
const { showToast } = useToast();

const redirectToLogin: () => Promise<void> = async () => {
if (!token) {
alert('로그인이 필요합니다.');
showToast('로그인이 필요합니다.', 'info');
try {
await router.push('/login');
} catch (error) {
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/queries/fridge/useGetIngredientList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { queryKeys } from '../queryKeys';
import { useBaseQuery } from '../useBaseQuery';

const useGetIngredientList = () => {
// const testApiEndpoint = 'https://jsonplaceholder.typicode.com/todos';

return useBaseQuery<IngredientType>(queryKeys.INGREDIENT(), '/ingrs');
};

Expand Down
1 change: 1 addition & 0 deletions src/hooks/queries/login/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as useGetKakaoToken } from './useGetKakaoToken';
14 changes: 14 additions & 0 deletions src/hooks/queries/login/useGetKakaoToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { queryKeys } from '../queryKeys';
import { useBaseQuery } from '../useBaseQuery';

const useGetKakaoToken = (code: string | null = '') => {
const { data } = useBaseQuery<{ data: { accessToken: string } }>(
queryKeys.KAKAO(),
`/users/kakao-login?code=${code}`,
);
if (data) {
localStorage.setItem('token', data.data.accessToken);
}
};

export default useGetKakaoToken;
3 changes: 2 additions & 1 deletion src/hooks/queries/queryKeys.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export const queryKeys = {
INGREDIENT: (id?: number) => ['ingredient', id] as const,
INGREDIENT: (id?: number) => (id ? ['ingredient', id] : ['ingredient']),
KAKAO: () => ['kakao'],
} as const;

export type QueryKeys = (typeof queryKeys)[keyof typeof queryKeys];
11 changes: 3 additions & 8 deletions src/hooks/queries/useBaseQuery.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
import axiosInstance from '@/api/axiosInstance';
import { useQuery } from '@tanstack/react-query';
import { useSuspenseQuery } from '@tanstack/react-query';

export const fetchData = async <T>(url: string) => {
const response = await axiosInstance.get<{ data: T }>(url);
return response.data;
};

export const useBaseQuery = <T>(queryKey: any, url: string) => {
return useQuery({
return useSuspenseQuery({
queryKey,
queryFn: async () =>
await fetchData<T>(url)
.then((res) => res.data)
.catch((error) => {
console.error(error);
}),
queryFn: async () => await fetchData<T>(url).then((res) => res.data),
});
};
33 changes: 24 additions & 9 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,16 @@ import Layout from '@/components/templates/Layout';
import '@/styles/globals.css';
import type { AppProps } from 'next/app';
import { RecoilRoot } from 'recoil';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
QueryClient,
QueryClientProvider,
QueryErrorResetBoundary,
} from '@tanstack/react-query';
import React from 'react';
import 'dayjs/locale/ko';
import dayjs from 'dayjs';
import { ErrorBoundary } from 'react-error-boundary';
import { ErrorFallback, SuspenseFallback } from '@/components/templates';
dayjs.locale('ko');

const theme = extendTheme({
Expand All @@ -26,14 +33,22 @@ const queryClient = new QueryClient({
export default function App({ Component, pageProps }: AppProps): JSX.Element {
return (
<QueryClientProvider client={queryClient}>
<RecoilRoot>
<ThemeProvider theme={theme}>
<CSSReset />
<Layout>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
</RecoilRoot>
<QueryErrorResetBoundary>
{({ reset }) => (
<ErrorBoundary onReset={reset} FallbackComponent={ErrorFallback}>
<React.Suspense fallback={<SuspenseFallback />}>
<RecoilRoot>
<ThemeProvider theme={theme}>
<CSSReset />
<Layout>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
</RecoilRoot>
</React.Suspense>
</ErrorBoundary>
)}
</QueryErrorResetBoundary>
</QueryClientProvider>
);
}
25 changes: 9 additions & 16 deletions src/pages/login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import MonstersImg from '@/assets/images/img_login_monsters.svg';
import KaKaoImg from '@/assets/images/img_login_kakao.svg';
import GoogleImg from '@/assets/images/img_login_google.svg';
import { type NextPage } from 'next';
import { useEffect } from 'react';
import { getKaKaoToken } from '@/api/login/getToken';
import { useGetKakaoToken } from '@/hooks/queries/login';

const LoginPage: NextPage = () => {
const kakaoURL = `https://kauth.kakao.com/oauth/authorize?client_id=${process.env.NEXT_PUBLIC_KAKAO_API_KEY}&redirect_uri=${process.env.NEXT_PUBLIC_KAKAO_REDIRECT_URI}&response_type=code`;
Expand All @@ -17,21 +16,15 @@ const LoginPage: NextPage = () => {
window.location.href = `${googleURL}&type=google`;
};

useEffect(() => {
const fetchData = async (): Promise<void> => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
// const type = urlParams.get('type');
// 구글 추가시 타입 redirect_uri 변경
const urlParams =
typeof window !== 'undefined'
? new URLSearchParams(window.location.search)
: null;
const code = urlParams?.get('code');

if (code) {
await getKaKaoToken(code);
}
};

// eslint-disable-next-line @typescript-eslint/no-floating-promises
fetchData();
}, []);
if (code) {
useGetKakaoToken(code);
}

return (
<section
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -10097,6 +10097,13 @@ react-element-to-jsx-string@^15.0.0:
is-plain-object "5.0.0"
react-is "18.1.0"

react-error-boundary@^4.0.12:
version "4.0.12"
resolved "https://registry.yarnpkg.com/react-error-boundary/-/react-error-boundary-4.0.12.tgz#59f8f1dbc53bbbb34fc384c8db7cf4082cb63e2c"
integrity sha512-kJdxdEYlb7CPC1A0SeUY38cHpjuu6UkvzKiAmqmOFL21VRfMhOcWxTCBgLVCO0VEMh9JhFNcVaXlV4/BTpiwOA==
dependencies:
"@babel/runtime" "^7.12.5"

[email protected]:
version "3.2.2"
resolved "https://registry.yarnpkg.com/react-fast-compare/-/react-fast-compare-3.2.2.tgz#929a97a532304ce9fee4bcae44234f1ce2c21d49"
Expand Down
Loading