프로젝트 코드 : https://github.com/Younngg/tripMatch
배포 페이지 : https://web-trip-match-1jx7m2gldef0u0j.gksl2.cloudtype.app/
기술적인 목표 보다는 협업에 대해 많이 고민했다.
내 목표는,
| 기간 | 팀원 | 기술 스택 |
|---|---|---|
| 3주 | 프론트엔드 5명, 백엔드 1명 | 언어 : TypeScript 프론트 : React, redux-toolkit, RTK query, styled-components, Cloudinary, toast-ui, 그 외 라이브러리 백엔드 : node.js, express, mongoDB, mongoose, jwt, Nodemailer, redis, 그 외 라이브러리 배포 : PM2, Nginx 협업 : Figma, GitLab, Swagger(API 명세) |



게시판이 총 3개이고, 게시글 삭제, 댓글 삭제에만 적용해도 총 4개의 모달이 필요하다. 처음엔 이를 하나의 모달로 만들어 재사용 가능하도록 했다. payload를 보내지 않고, action 자체에서 boolean값을 바꾸도록 작성했다.
const DeleteModal: React.FC<DeleteModalProps> = ({ onDelete }) => {
const dispatch = useAppDispatch();
const elementName = useAppSelector((state) => state.modal.element);
const onCancle = () => dispatch(closeModal());
return (
<ModalCard>
<div className="modalCard">
<ModalTitle>{elementName} 삭제</ModalTitle>
<p>이 {elementName}을 삭제하시겠습니까?</p>
<ButtonContainer>
<button onClick={onCancle}>취소</button>
<button>삭제</button>
</ButtonContainer>
</div>
</ModalCard>
);
};
export default DeleteModal;
그러다 동행 신청, 동행 신청 취소, 탈퇴, 프로필 조회, 축제 정보 조회 등 많은 기능에서 모달을 사용하게 되었다. 모달의 제목과 내용, 버튼 텍스트를 바꿀 수 있고, isShow 여부를 알 수 있게 payload의 type을 바꾸었다.
interface ModalTextType {
title: string;
content: string;
leftButton?: string;
rightButton: string;
}
interface ModalType {
show: boolean;
modalText: null | ModalTextType; // [title, content, button text, cancleButton text]
}
const initialState: ModalType = { show: false, modalText: null };
export const modalSlice = createSlice({
name: "modal",
initialState: initialState,
reducers: {
showModal: (state, action) => ({ show: true, modalText: action.payload }),
closeModal: (state) => ({ ...state, show: false }),
},
});
export const { showModal, closeModal } = modalSlice.actions;
const Modal: React.FC<ModalProps> = ({ callBackFn }) => {
const dispatch = useAppDispatch();
const text = useAppSelector((state) => state.modal.modalText);
const onCancle = () => dispatch(closeModal());
const onExcute = () => {
callBackFn();
dispatch(closeModal());
};
return (
<ModalCard>
<div className="modalCard">
<ModalTitle>{text && text.title}</ModalTitle>
<p>{text && text.content}</p>
<ButtonContainer>
<button onClick={onCancle}>{text?.leftButton || "취소"}</button>
<button onClick={onExcute}>{text && text.rightButton}</button>
</ButtonContainer>
</div>
</ModalCard>
);
};
초반에 데이터 패칭 로직은 redux로 관리하지 않는 상태였다. 그 때 전역으로 관리하는 상태는 modal 밖에 없었는데, 이렇게만 사용한다면 redux가 불필요해지는 것 같아 RTK query를 적용하자는 의견을 냈다.
export const freePostApi = createApi({
reducerPath: "freePostApi",
tagTypes: ["FreePost", "MatchPost", "SearchPost"],
baseQuery: authAxiosBaseQuery({
baseUrl: "http://kdt-sw3-team08.elicecoding.com:3003/api/",
}),
endpoints: (builder) => ({
getAllFreePost: builder.query<
{ totalCount: number; communities: FreePostType[] },
{ page?: number; region?: string; perPage?: number; keyword?: string }
>({
query: ({ page, region, perPage, keyword }) => {
return {
url: "main/communities",
method: "get",
params: { page, region, perPage, keyword },
};
},
providesTags: (result, error, arg) =>
result
? [
"FreePost",
...result.communities.map((post) => ({
type: "FreePost" as const,
id: post.communityId,
})),
]
: ["FreePost"],
}),
// ...
access token과 refresh token을 사용하고 있었는데, access token이 만료될 때 refresh token을 요청하는 코드를 매 데이터 패칭 로직마다 작성하기 번거롭고, 코드를 관리하기 어려워져 코치님의 의견으로 axios interceptor를 추가하게 되었다. axios interceptor로 header 관련 로직을 처리했다.
공식문서 : https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#axios-basequery
// 로그인이 필요하지 않은 기능에 적용할 baseQuery
export const axiosBaseQuery =
(
{ baseUrl }: { baseUrl: string } = { baseUrl: "" },
): BaseQueryFn<
{
url: string;
method: AxiosRequestConfig["method"];
data?: AxiosRequestConfig["data"];
params?: AxiosRequestConfig["params"];
},
unknown,
unknown
> =>
async ({ url, method, data, params }) => {
try {
const result = await axios({
url: baseUrl + url,
method,
data,
params,
});
if (result.status === 204) {
throw new Error("204 에러입니다.");
}
return { data: result.data };
} catch (axiosError) {
const err = axiosError as AxiosError;
return {
error: {
status: err.response?.status,
data: err.response?.data || err.message,
},
};
}
};
// 로그인이 필요한 않은 기능에 적용할 baseQuery
export const authAxiosBaseQuery =
(
{ baseUrl }: { baseUrl: string } = { baseUrl: "" },
): BaseQueryFn<
{
url: string;
method: AxiosRequestConfig["method"];
data?: AxiosRequestConfig["data"];
params?: AxiosRequestConfig["params"];
},
unknown,
unknown
> =>
async ({ url, method, data, params }) => {
try {
const result = await authAxios({
url: baseUrl + url,
method,
data,
params,
});
// ... 위와 같음
};

authAxiosBaseQuery 적용 예시
그 밖에 axios와 fetch의 차이 및 axios로 통일하고자 한 이유
fetch()는 then 메서드에서 처리된 promise를 반환한다. axios는 응답 데이터를 기본적으로 JSON 타입으로 사용할 수 있고, 응답 객체의 data 프로퍼티로 받아올 수 있다. 또 responseType을 지정해 JSON 타입을 재정의 할 수 있다.
axios로 post 요청을 할 때에도 객체를 문자열로 변환해준다. fetch는 JSON.stringify()를 사용해야 한다.RTK query의 fetchBaseQuery는 내부에서 JSON 관련 처리를 다 해결해주긴 하지만, 똑같은 interceptor 로직을 두번 작성하는 것이 불필요하게 느껴졌다.
또 로그인 관련 데이터를 전역 상태로 관리하고 있지 않기 때문에 refresh token 요청을 axios interceptor에서 전담하고, rtk query 쪽에서는 커스텀 axios만 가져다 쓰고 따로 작성하지 않음으로써 분리를 하고자 했다.
자유게시글, 동행게시글 작성 페이지는 toast ui 라이브러리를 사용했다. toast ui에는 마크다운 기능이 있는데, 공식문서에서 마크다운 기능을 제거할 api를 찾지 못했다. toast ui에서 제공하는 viewer도 사용 가능한 것 같아 보였는데 viewer는 react 문서가 없어서 이것저것 시도해보다가 결국 사용하지 못했다.
interface EditorProps {
placeholder?: string;
initialValue?: string;
contentRef?: React.LegacyRef<ToastEditor>;
}
const Editor: React.FC<EditorProps> = ({
placeholder,
initialValue,
contentRef,
}) => {
return (
<Container>
<ToastEditor
ref={contentRef}
placeholder={placeholder || "내용을 작성해주세요."}
initialValue={initialValue || " "}
previewStyle="vertical"
height="500px"
initialEditType="wysiwyg"
useCommandShortcut={true}
language="ko-KR"
toolbarItems={[
["heading", "bold", "italic", "strike"],
["ul", "ol", "task"],
["link"],
]}
/>
</Container>
);
};
export default Editor;
const Container = styled.div`
margin: 10px 0;
`;
import MarkdownViewer from "react-showdown";
import "@toast-ui/editor/dist/toastui-editor-viewer.css";
const MarkdownView: React.FC<{ content: string | undefined }> = ({
content,
}) => {
return (
<PostContent>
<MarkdownViewer
markdown={content || ""}
options={{ tables: true, emoji: true }}
className="toastui-editor-contents"
/>
</PostContent>
);
};
export default MarkdownView;
const PostContent = styled.article`
min-height: 300px;
padding: 40px 0;
line-height: 1.7;
.toastui-editor-contents {
font-size: ${(props) => props.theme.font.M};
font-family: "S-CoreDream-3Light";
}
`;
const [
onCreateComment,
{ isError: isErrorCreateComment, isSuccess: isSuccessCreateComment },
] = useCreateCommentMutation();
const location = useLocation();
const currentPath = location.pathname.split("/").slice(1, 3);
useEffect(() => {
if (isErrorCreateComment) {
alert("댓글 작성에 실패했습니다.");
} else if (isSuccessCreateComment) {
window.location.reload();
}
}, [isErrorCreateComment, isSuccessCreateComment]);typeScript로 react 프로젝트를 할 때 자주 사용하는 type을 분리하고, 그 안에서 response 와 request 데이터 type을 분리해야 한다는 것을 배웠다. 이번 프로젝트에선 type만 분리하고, response에 추가적으로 들어오는 값은 optional로 표기했다. 그래서 컴포넌트 내에서도 props를 optional로 내려주는 경우가 종종 발생했다. 처음에 response와 request를 나눠서 작성했다면 typescript의 장점을 더 많이 느낄 수 있었을텐데, 프로젝트 막바지에 알게 되어 아쉬웠다.
위와 같은 방법을 사용하여 props로 optional 값을 내려주는 것을 자제해야겠다.
RTK query, 모달 등 전역으로 관리해야 할 상태는 미리 어떤 컴포넌트에서 사용할지 계획을 짜고 시작하는 것이 좋을 것 같다. 물론 프로젝트를 진행하며 바뀌기도 하겠지만, 계획을 한 것과 하지 않은 것엔 큰 차이가 있다고 생각한다.
refresh를 요청했으나 한번 더 401이 왔을 때(refresh token 또한 만료가 되었을 때) 로그아웃 처리를 안 했다.. 이는 개인적으로 리팩토링을 진행하며 보완해야겠다.
modal slice를 만들었는데, 같은 페이지 안에서 다른 컴포넌트를 구현하는 팀원들이 자신이 맡은 부분 중 상위 컴포넌트에 modal 을 적용했더니 한꺼번에 여러개가 불러와지는 상황이 발생했다.
UI/UX에 대한 공부가 부족했다. 공부를 제대로 하지 않고 다른 페이지를 예시로 말하거나, 내 주관적인 생각으로 말하는 경우가 많았다. 이를 정확한 근거를 들고 말했다면 설득하기 더 쉽고, 나도 더 자신있게 의견을 말할 수 있었을 것이다.
에디터, modal은 필요한 것들을 props로 내려주었다. editor같은 경우는 ref만 받아 toast ui의 getHTML()로 데이터를 받아왔다. 컴포넌트를 재사용함으로써 코드의 양을 줄이는 것도 좋았지만, 모든 작성 페이지의 데이터를 useRef로 받아옴으로써 코드의 스타일을 통일할 수 있다는 점도 좋았다.
공통적인 font 크기와 color는 styled-components의 DefaultTheme로 지정해두어서 필요하면 props로 얼마든지 꺼낼 수 있었다. 또 모달의 경우, 공통적인 style을 작성하여 스타일을 관리하기 편했다. 추가적인 스타일을 적용하려면 styled(style컴포넌트)로 상속시켜주었다. 컴포넌트를 조합하여 하나의 웹페이지를 구성한다는 react 기반의 웹 개발 방식과 styled-components의 장점이 우리 프로젝트에서 잘 어우러졌다고 생각한다.
RTK query를 사용함으로써 UI와 data fetching 로직을 분리시킬 수 있어서 좋았다. api 명세 등의 수정사항이 생길 때 api slice 안에서만 수정할 수 있어서 편리했다. 또 상태가 업데이트 되면 캐시가 무효화되면서 다시 데이터를 불러오기 때문에, useEffect로 data fetching을 하지 않아도 되었다. 또 isError, isSuccess 등으로 에러 처리를 할 수 있어 편리했다.
axios interceptor를 통해 refresh token을 요청하는 로직을 여러번 작성하지 않아도 되어서 좋았다.
무엇보다 이번 프로젝트를 통해 공식문서를 보는 눈을 키웠다. 이전엔 영어로 된 공식문서가 보기 싫어서.. 한국어로 번역한 블로그를 찾아보곤 했는데, 이번엔 원하는 정보를 한국어로 찾기 어려워 공식문서를 많이 읽었다. 한국어로 번역해서 원하는 부분을 찾은 뒤에, 다시 영어로 읽으면 이해하기 한결 쉬워진다는 꿀팁이 생겼다. axiosBaseQuery 커스텀도 공식문서를 열심히 읽지 않았다면 몰랐을 것이다.
또 협업에 한층 더 익숙해졌고, 큰 즐거움을 느꼈다. 의견을 내는 게 너무 재미있었다. 낯을 가리는 성격이라 평소엔 말이 없는데, 프로젝트만 하면 엄청 수다스러워진다. 항상 지금보다 더 나은 로직이, UI가 있을 것 같다는 생각이 들어… 말을 멈출 수가 없다ㅠㅠ 그래서 나중엔 팀원들이 안 좋게 받아들일까봐.. 걱정하기도 했다. 그래도 취업을 하고 나면 이만큼 의견을 자유롭게 낼 수 없을 것 같아 지금 마음껏 즐기기로 했다…ㅎㅎ
styled-components를 사용하며 느꼈던 장단점 : https://velog.io/@younngg1012/styled-components
1차 프로젝트 회고 : https://velog.io/@younngg1012/eggfried