Skip to content

Commit

Permalink
utils의 fetch 함수 리팩터링, ErrorBoundary 구현, query를 이용한 에러핸들링 (#294)
Browse files Browse the repository at this point in the history
* refactor: (#158) try-catch 구문으로 변경
Co-authored-by: 김영길/KIM YOUNG GIL <Gilpop8663@users.noreply.github.com>
Co-authored-by: chsua <chsua@users.noreply.github.com>

* feat: (#158) ErrorBoundary 구현

* refactor: (#158) 데이터 생성 시 에러 핸들링 코드 이동
  • Loading branch information
inyeong-kang authored Aug 9, 2023
1 parent a57e8c3 commit 726ee59
Show file tree
Hide file tree
Showing 7 changed files with 184 additions and 103 deletions.
2 changes: 1 addition & 1 deletion frontend/src/api/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const createCart = async () => {
};

export const editCart = async () => {
return await putFetch<Cart, { id: number }>('api/cart', { id: 12, text: '생성' });
return await putFetch<{ id: number }>('api/cart', { id: 12 });
};

// remove or delete
Expand Down
7 changes: 0 additions & 7 deletions frontend/src/components/PostForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,6 @@ export default function PostForm({ data, mutate, isError, error }: PostFormProps
formData.append('request', JSON.stringify(updatedPostTexts));

mutate(formData);

if (isError && error instanceof Error) {
alert(error.message);
return;
}

navigate('/');
}
};

Expand Down
10 changes: 7 additions & 3 deletions frontend/src/components/post/PostListPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { AuthContext } from '@hooks/context/auth';
import { useCategoryList } from '@hooks/query/category/useCategoryList';
import { useDrawer } from '@hooks/useDrawer';

import ErrorBoundary from '@pages/ErrorBoundary';

import AddButton from '@components/common/AddButton';
import Dashboard from '@components/common/Dashboard';
import Drawer from '@components/common/Drawer';
Expand Down Expand Up @@ -40,9 +42,11 @@ export default function PostListPage() {
/>
</Drawer>
</S.DrawerWrapper>
<Suspense fallback={<Skeleton />}>
<PostList />
</Suspense>
<ErrorBoundary fallback={<div>에러발생</div>}>
<Suspense fallback={<Skeleton />}>
<PostList />
</Suspense>
</ErrorBoundary>
<S.ButtonContainer>
<UpButton onClick={scrollToTop} />
<S.AddButtonWrapper to={PATH.POST_WRITE}>
Expand Down
33 changes: 18 additions & 15 deletions frontend/src/hooks/query/post/useCreatePost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,23 @@ import { QUERY_KEY } from '@constants/queryKey';

export const useCreatePost = () => {
const queryClient = useQueryClient();
const { mutate, isLoading, isError, error } = useMutation((post: FormData) => createPost(post), {
onSuccess: () => {
queryClient.invalidateQueries([
QUERY_KEY.POSTS,
SORTING.LATEST,
STATUS.PROGRESS,
DEFAULT_CATEGORY_ID,
DEFAULT_KEYWORD,
]);
},
onError: error => {
window.console.log('createPost error', error);
},
});
const { mutate, isLoading, isSuccess, isError, error } = useMutation(
(post: FormData) => createPost(post),
{
onSuccess: () => {
queryClient.invalidateQueries([
QUERY_KEY.POSTS,
SORTING.LATEST,
STATUS.PROGRESS,
DEFAULT_CATEGORY_ID,
DEFAULT_KEYWORD,
]);
},
onError: error => {
window.console.log('createPost error', error);
},
}
);

return { mutate, isLoading, isError, error };
return { mutate, isLoading, isSuccess, isError, error };
};
39 changes: 39 additions & 0 deletions frontend/src/pages/ErrorBoundary.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Component, ErrorInfo, ReactNode } from 'react';

interface ErrorBoundaryProps {
children: ReactNode;
fallback: ReactNode;
}

interface ErrorBoundaryState {
hasError: boolean;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
#errorMessage = '';

constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}

static getDerivedStateFromError(error: Error) {
return { hasError: true };
}

componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// You can also log the error to an error reporting service
window.console.log(error, errorInfo);
this.#errorMessage = error.message;
}

render() {
if (this.state.hasError) {
return <div>{this.#errorMessage}</div>;
}

return this.props.children;
}
}

export default ErrorBoundary;
17 changes: 16 additions & 1 deletion frontend/src/pages/post/CreatePost/index.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,32 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

import { useCreatePost } from '@hooks/query/post/useCreatePost';

import Layout from '@components/common/Layout';
import PostForm from '@components/PostForm';

export default function CreatePost() {
const { mutate, isError, error } = useCreatePost();
const navigate = useNavigate();

const { mutate, isSuccess, isError, error } = useCreatePost();

useEffect(() => {
window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
}, []);

useEffect(() => {
if (isSuccess) {
navigate('/');
}
}, [isSuccess, navigate]);

useEffect(() => {
if (isError && error instanceof Error) {
alert(error.message);
}
}, [isError, error]);

return (
<Layout isSidebarVisible={false}>
<PostForm mutate={mutate} isError={isError} error={error} />
Expand Down
179 changes: 103 additions & 76 deletions frontend/src/utils/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,102 +23,129 @@ const makeFetchMultiHeaders = () => {
};

export const getFetch = async <T>(url: string): Promise<T> => {
const response = await fetch(url, {
method: 'GET',
headers: makeFetchHeaders(),
});

if (!response.ok) {
throw new Error('에러');
try {
const response = await fetch(url, {
method: 'GET',
headers: makeFetchHeaders(),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}

const data = await response.json();

return data;
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}

const data = await response.json();
return data;
};

export const postFetch = async <T>(url: string, body: T): Promise<void> => {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
headers: makeFetchHeaders(),
});

if (!response.ok) {
throw new Error('에러');
export const postFetch = async <T>(url: string, body: T) => {
try {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(body),
headers: makeFetchHeaders(),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}

// const data = await response.json();

return;
};

export const putFetch = async <T, R>(url: string, body: T): Promise<R | void> => {
const response = await fetch(url, {
method: 'PUT',
body: JSON.stringify(body),
headers: makeFetchHeaders(),
});

// const data = await response.json();

if (!response.ok) {
throw new Error('error');
export const putFetch = async <T>(url: string, body: T) => {
try {
const response = await fetch(url, {
method: 'PUT',
body: JSON.stringify(body),
headers: makeFetchHeaders(),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}

return;
};

export const patchFetch = async <T>(url: string, body?: T) => {
const response = await fetch(url, {
method: 'PATCH',
headers: makeFetchHeaders(),
body: JSON.stringify(body),
});

if (!response.ok) {
throw new Error('에러');
try {
const response = await fetch(url, {
method: 'PATCH',
headers: makeFetchHeaders(),
body: JSON.stringify(body),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}

return response;
};

export const deleteFetch = async (url: string) => {
const response = await fetch(url, {
method: 'DELETE',
headers: makeFetchHeaders(),
});

return response;
try {
const response = await fetch(url, {
method: 'DELETE',
headers: makeFetchHeaders(),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}
};

export const multiPostFetch = async (url: string, body: FormData) => {
const response = await fetch(url, {
method: 'POST',
body,
headers: makeFetchMultiHeaders(),
});

// const data = await response.json();

if (!response.ok) {
throw new Error('error');
try {
const response = await fetch(url, {
method: 'POST',
body,
headers: makeFetchMultiHeaders(),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}

return;
};

export const multiPutFetch = async (url: string, body: FormData) => {
const response = await fetch(url, {
method: 'PUT',
body,
headers: makeFetchMultiHeaders(),
});

const data = await response.json();

if (!response.ok) {
throw new Error(data.message);
try {
const response = await fetch(url, {
method: 'PUT',
body,
headers: makeFetchMultiHeaders(),
});

if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
} catch (e) {
const error = e as Error;
throw new Error(error.message);
}

return data;
};

0 comments on commit 726ee59

Please sign in to comment.