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

[#455] [모임 상세] 모임 가입 문제 페이지 #462

Merged
merged 9 commits into from
Dec 18, 2023
104 changes: 104 additions & 0 deletions src/app/group/[groupId]/join/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use client';

import { notFound, useRouter } from 'next/navigation';
import { SubmitHandler, useForm } from 'react-hook-form';

import useJoinBookGroup from '@/hooks/group/useJoinBookGroup';

import SSRSafeSuspense from '@/components/SSRSafeSuspense';
import Loading from '@/v1/base/Loading';
import Input from '@/v1/base/Input';
import InputLength from '@/v1/base/InputLength';
import ErrorMessage from '@/v1/base/ErrorMessage';
import BottomActionButton from '@/v1/base/BottomActionButton';
import BookGroupNavigation from '@/v1/bookGroup/BookGroupNavigation';

type JoinFormValues = {
answer: string;
};

const JoinBookGroupPage = ({
params: { groupId },
}: {
params: { groupId: number };
}) => {
return (
<SSRSafeSuspense fallback={<Loading fullpage />}>
<BookGroupNavigation groupId={groupId}>
<BookGroupNavigation.BackButton
href={`/group/${groupId}`}
routeOption="replace"
/>
<BookGroupNavigation.Title />
</BookGroupNavigation>
<BookGroupJoinForm groupId={groupId} />
</SSRSafeSuspense>
);
};

const BookGroupJoinForm = ({ groupId }: { groupId: number }) => {
const router = useRouter();
const { isMember, hasPassword, question, joinBookGroup } =
useJoinBookGroup(groupId);

if (isMember || !hasPassword) {
notFound();
}

const {
register,
watch,
handleSubmit,
formState: { errors },
} = useForm<JoinFormValues>({ mode: 'all' });

const submitJoinForm: SubmitHandler<JoinFormValues> = ({ answer }) => {
joinBookGroup({
answer,
onSuccess: () => router.replace(`/group/${groupId}`),
});
};

return (
<form
className="mt-[2.5rem] flex flex-col gap-[2.5rem]"
onSubmit={handleSubmit(submitJoinForm)}
>
<p className="whitespace-pre-line text-2xl font-bold leading-snug">
{`문제를 맞추면
모임에 가입할 수 있어요`}
</p>
<div className="flex flex-col gap-[1.5rem]">
<p className="text-sm">{question}</p>
<div className="flex flex-col gap-[0.5rem]">
<Input
{...register('answer', {
required: '정답을 입력해주세요',
pattern: {
value: /^\S*$/g,
message: '띄어쓰기 없이 정답을 입력해주세요.',
},
minLength: { value: 1, message: '1자 이상 입력해주세요.' },
maxLength: { value: 10, message: '10자 이하 입력해주세요.' },
})}
placeholder="띄어쓰기 없이 정답을 입력해주세요"
error={!!errors.answer}
/>
<div className="flex flex-row-reverse justify-between gap-[0.4rem]">
<InputLength
isError={!!errors.answer}
currentLength={watch('answer')?.length}
maxLength={10}
/>
{errors.answer && (
<ErrorMessage>{errors.answer.message}</ErrorMessage>
)}
</div>
</div>
</div>
<BottomActionButton type="submit">제출하기</BottomActionButton>
</form>
);
};

export default JoinBookGroupPage;
56 changes: 56 additions & 0 deletions src/hooks/group/useJoinBookGroup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { isAxiosErrorWithCustomCode } from '@/utils/helpers';
import { SERVICE_ERROR_MESSAGE } from '@/constants';
import groupAPI from '@/apis/group';
import useToast from '@/v1/base/Toast/useToast';
import { useBookGroupJoinInfo } from '@/queries/group/useBookGroupQuery';

const useJoinBookGroup = (groupId: number) => {
const { data: bookGroupJoinData, refetch } = useBookGroupJoinInfo(groupId);
const { isExpired, isMember, hasPassword, question } = bookGroupJoinData;

const toast = useToast();

const joinBookGroup = async ({
answer,
onSuccess,
}: {
answer?: string;
onSuccess?: () => void;
}) => {
try {
await groupAPI.joinGroup({ bookGroupId: groupId, password: answer });
toast.show({ message: '🎉 모임에 가입되었어요! 🎉', type: 'success' });
onSuccess && onSuccess();
} catch (error) {
if (!isAxiosErrorWithCustomCode(error)) {
toast.show({ message: '잠시 후 다시 시도해주세요', type: 'error' });
return;
}

const { code } = error.response.data;
const message = SERVICE_ERROR_MESSAGE[code];
const isWrongAnswerErrorCode = code === 'BG3';

if (isWrongAnswerErrorCode) {
toast.show({
message: '정답이 아니에요. 다시 시도해주세요!',
type: 'error',
});
return;
}

toast.show({ message, type: 'error' });
}
};

return {
isExpired,
isMember,
hasPassword,
question,
refetch,
joinBookGroup,
};
};

export default useJoinBookGroup;
59 changes: 49 additions & 10 deletions src/v1/bookGroup/BookGroupNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,6 @@ import {

const NavigationContext = createContext({} as { groupId: number });

const getTargetChildren = (children: ReactNode, Target: () => JSX.Element) => {
const childrenArray = Children.toArray(children);

return childrenArray.filter(
child => isValidElement(child) && child.type === (<Target />).type
);
};

const BookGroupNavigation = ({
groupId,
children,
Expand Down Expand Up @@ -55,11 +47,38 @@ const BookGroupNavigation = ({
);
};

const BackButton = () => {
type BackButtonProps =
| {
routeOption: 'push';
href: string;
}
| {
routeOption: 'replace';
href: string;
}
| {
routeOption?: 'back';
};

const BackButton = (props: BackButtonProps) => {
const { routeOption } = props;
const router = useRouter();

const handleClick = () => {
switch (routeOption) {
case 'push':
return router.push(props.href);
case 'replace':
return router.replace(props.href);
case 'back':
return router.back();
default:
return router.back();
}
};

return (
<a onClick={router.back}>
<a onClick={handleClick}>
<IconArrowLeft />
</a>
);
Expand Down Expand Up @@ -97,3 +116,23 @@ export default BookGroupNavigation;
const TitleSkeleton = () => (
<div className="h-[1.5rem] w-[40%] animate-pulse bg-black-400"></div>
);

const BackButtonType = (<BackButton />).type;
const TitleType = (<Title />).type;
const MenuButtonType = (<MenuButton />).type;
const WriteButtonType = (<WriteButton />).type;
gxxrxn marked this conversation as resolved.
Show resolved Hide resolved

const getTargetChildren = (
children: ReactNode,
targetType:
| typeof BackButtonType
| typeof TitleType
| typeof MenuButtonType
| typeof WriteButtonType
) => {
const childrenArray = Children.toArray(children);

return childrenArray.find(
child => isValidElement(child) && child.type === targetType
);
};
gxxrxn marked this conversation as resolved.
Show resolved Hide resolved
42 changes: 7 additions & 35 deletions src/v1/bookGroup/detail/JoinBookGroupButton.tsx
Original file line number Diff line number Diff line change
@@ -1,49 +1,21 @@
import { usePathname, useRouter } from 'next/navigation';

import { SERVICE_ERROR_MESSAGE } from '@/constants';
import { isAxiosErrorWithCustomCode } from '@/utils/helpers';

import { useBookGroupJoinInfo } from '@/queries/group/useBookGroupQuery';
import groupAPI from '@/apis/group';
import useToast from '@/v1/base/Toast/useToast';
import useJoinBookGroup from '@/hooks/group/useJoinBookGroup';
import BottomActionButton from '@/v1/base/BottomActionButton';

const JoinBookGroupButton = ({ groupId }: { groupId: number }) => {
const _router = useRouter();
const _pathname = usePathname();
const toast = useToast();

const {
data: { isExpired, isMember, hasPassword },
refetch,
} = useBookGroupJoinInfo(groupId);

const joinBookGroup = async () => {
try {
await groupAPI.joinGroup({ bookGroupId: groupId });
toast.show({ message: '모임에 가입했어요!', type: 'success' });
refetch();
} catch (error) {
if (!isAxiosErrorWithCustomCode(error)) {
toast.show({ message: '잠시 후 다시 시도해주세요.', type: 'error' });
return;
}

const { code } = error.response.data;
const message = SERVICE_ERROR_MESSAGE[code];

toast.show({ message, type: 'error' });
}
};
const router = useRouter();
const pathname = usePathname();
const { isExpired, isMember, hasPassword, joinBookGroup, refetch } =
useJoinBookGroup(groupId);

const handleButtonClick = async () => {
if (hasPassword) {
// TODO: 모임 가입문제 페이지 생성 후 연결
// router.push(`${pathname}/join`);
router.replace(`${pathname}/join`);
return;
}

joinBookGroup();
joinBookGroup({ onSuccess: refetch });
};

if (isMember) {
Expand Down