Skip to content
Merged
5 changes: 4 additions & 1 deletion src/apis/letterDetail.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@ import client from './client';
const getLetter = async (
letterId: string,
setLetterState: React.Dispatch<React.SetStateAction<LetterDetail | null>>,
callBack?: () => void,
) => {
try {
const res = await client.get(`/api/letters/${letterId}`);
setLetterState(res.data.data);
if (callBack) callBack();
console.log(res);
} catch (error) {
console.error(error);
}
};

const deleteLetter = async (letterId: string) => {
const deleteLetter = async (letterId: string, callBack?: () => void) => {
try {
console.log(`/api/letters/${letterId}`);
const res = await client.delete(`/api/letters/${letterId}`);
if (callBack) callBack();
console.log(res);
} catch (error) {
console.error(error);
Expand Down
11 changes: 5 additions & 6 deletions src/apis/write.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
import client from './client';

const postLetter = async (
data: LetterRequest,
setState?: React.Dispatch<React.SetStateAction<boolean>>,
) => {
const postLetter = async (data: LetterRequest, callBack?: () => void) => {
try {
const res = await client.post('/api/letters', data);
if (setState) setState(true);
if (callBack) callBack();
console.log(res);
} catch (error) {
console.error(error);
}
};

const getPrevLetter = async (
setPrevLetterState: React.Dispatch<React.SetStateAction<PrevLetter[]>>,
letterId: string,
setPrevLetterState: React.Dispatch<React.SetStateAction<PrevLetter[]>>,
callBack?: () => void,
) => {
try {
const res = await client.get(`/api/letters/${letterId}/previous`);
setPrevLetterState(res.data.data);
if (callBack) callBack();
console.log(res);
} catch (error) {
console.error(error);
Expand Down
21 changes: 12 additions & 9 deletions src/components/ResultLetter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ import LetterWrapper from './LetterWrapper';
export default function ResultLetter({
categoryName = 'CONSOLATION',
title,
zipCode = 'error',
}: {
categoryName: Category;
title: string;
zipCode?: string;
}) {
const address = '1A3E2';
const date = new Date();
const today = `${date.getFullYear()}년 ${date.getMonth() + 1}월 ${date.getDate()}일`;

Expand All @@ -26,14 +27,16 @@ export default function ResultLetter({
<div className="flex flex-col gap-[5px]">
<span className="caption-sb text-gray-60">{today}</span>
<div className="flex gap-1">
{address.split('').map((spell, idx) => (
<span
className="caption-r flex h-6 w-6 items-center justify-center rounded-sm bg-white/40"
key={idx}
>
{spell}
</span>
))}
{zipCode.split('').map((spell, idx) => {
return (
<span
className="caption-r flex h-6 w-6 items-center justify-center rounded-sm bg-white/40"
key={idx}
>
{spell}
</span>
);
})}
</div>
</div>
</div>
Expand Down
40 changes: 14 additions & 26 deletions src/pages/Write/CategorySelect.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { useState } from 'react';
import { Link } from 'react-router';

import { postLetter } from '@/apis/write';
import BackButton from '@/components/BackButton';
import PageTitle from '@/components/PageTitle';
import CategoryList from '@/pages/Write/components/CategoryList';
import useWrite from '@/stores/writeStore';
Expand All @@ -13,33 +11,20 @@ import WritePageButton from './components/WritePageButton';
export default function CategorySelect({
setStep,
prevLetter,
send,
setSend,
}: {
setStep: React.Dispatch<React.SetStateAction<Step>>;
prevLetter: PrevLetter[];
send: boolean;
setSend: React.Dispatch<React.SetStateAction<boolean>>;
}) {
const letterTitle = useWrite((state) => state.letterTitle);
const letterText = useWrite((state) => state.letterText);
const category = useWrite((state) => state.category);
const paperType = useWrite((state) => state.paperType);
const fontType = useWrite((state) => state.fontType);

const [send, setSend] = useState<boolean>(false);

const LETTER_REQUEST: LetterRequest = {
receiver: null,
parentLetterId: null,
title: letterTitle,
content: letterText,
category: category,
paperType: paperType,
fontType: fontType,
};
const letterRequest = useWrite((state) => state.letterRequest);

return (
<>
<div className="flex w-full grow flex-col items-center">
<div className="absolute left-0 flex w-full items-center justify-between px-5">
<BackButton />
{!send && prevLetter.length <= 0 && (
<WritePageButton
text="이전 단계"
Expand All @@ -60,9 +45,9 @@ export default function CategorySelect({
{/* 카테고리 선택 컴포넌트 */}
{!send && prevLetter.length <= 0 && <CategoryList />}

{prevLetter.length > 0 && (
{send && prevLetter.length > 0 && (
<div className="mt-25 flex w-full max-w-[300px] flex-col items-center gap-5">
<ResultLetterAnimation categoryName="답변자" />
<ResultLetterAnimation />
<div className="animate-show-text flex flex-col items-center opacity-0">
<span className="body-sb text-gray-60">작성하신 편지는</span>
<span className="body-sb text-gray-60">
Expand All @@ -74,9 +59,9 @@ export default function CategorySelect({
</div>
)}

{send && (
{send && prevLetter.length <= 0 && (
<div className="mt-25 flex w-full max-w-[300px] flex-col items-center gap-5">
<ResultLetterAnimation categoryName={category} />
<ResultLetterAnimation />
<span className="animate-show-text body-sb text-gray-60 opacity-0">
두근두근! 답장이 언제 올까요?
</span>
Expand All @@ -94,8 +79,11 @@ export default function CategorySelect({
<button
className="bg-primary-3 body-m mt-auto flex h-10 w-full items-center justify-center rounded-lg"
onClick={() => {
if (category) {
postLetter(LETTER_REQUEST, setSend);
if (letterRequest.category) {
postLetter(letterRequest, () => {
console.log(letterRequest);
setSend(true);
});
// setSend(true);
} else {
alert('우표 선택을 해주세요');
Expand Down
63 changes: 41 additions & 22 deletions src/pages/Write/LetterEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { useRef } from 'react';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router';
import { twMerge } from 'tailwind-merge';

import { postLetter } from '@/apis/write';
import BackButton from '@/components/BackButton';
import WritePageButton from '@/pages/Write/components/WritePageButton';
import { FONT_TYPE_OBJ } from '@/pages/Write/constants';
Expand All @@ -10,26 +12,35 @@ import useWrite from '@/stores/writeStore';
export default function LetterEditor({
setStep,
prevLetter,
setSend,
searchParams,
}: {
setStep: React.Dispatch<React.SetStateAction<Step>>;
prevLetter: PrevLetter[];
setSend: React.Dispatch<React.SetStateAction<boolean>>;
searchParams: URLSearchParams;
}) {
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const location = useLocation();
const [randomMatched, setRandomMatched] = useState<boolean>(false);

const fontType = useWrite((state) => state.fontType);
const letterRequest = useWrite((state) => state.letterRequest);
const setLetterRequest = useWrite((state) => state.setLetterRequest);

const letterTitle = useWrite((state) => state.letterTitle);
const setLetterTitle = useWrite((state) => state.setLetterTitle);

const letterText = useWrite((state) => state.letterText);
const setLetterText = useWrite((state) => state.setLetterText);
useEffect(() => {
if (location.state?.randomMatched) {
setRandomMatched(true);
}
}, [location.state?.randomMatched]);

const handleResizeHeight = () => {
if (textareaRef.current !== null) {
textareaRef.current.style.height = 'auto'; //height 초기화
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
useEffect(() => {
if (prevLetter.length > 0) {
setLetterRequest({
receiverId: prevLetter[0].memberId,
parentLetterId: Number(searchParams.get('letterId')),
Copy link
Collaborator

Choose a reason for hiding this comment

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

searchParams.get('letterId')가 useEffect 실행 시마다 호출되는 걸로 보이는데, 한 번만 호출하고 변수로 저장해 두는 건 어떨까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

오오 한번 해보겠습니다!👍👍

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

코드를 살펴봤는데 다른 의존성들이 딱 한번만 실행되고 더 실행안되는 코드들이라 useEffect가 딱 한번만 발생할거 같아서 이대로 두겠습니다!!(변수로 저장하니깐 lint가 또 뭐라해요 ㅠ)

Copy link
Collaborator

Choose a reason for hiding this comment

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

아하 네 좋습니다!

category: prevLetter[0].category,
});
}
};
}, [prevLetter, searchParams, setLetterRequest]);

return (
<div className="flex grow flex-col pb-15">
Expand All @@ -40,8 +51,17 @@ export default function LetterEditor({
<WritePageButton
text="답장 전송"
onClick={() => {
if (letterTitle.trim() !== '' && letterText.trim() !== '') {
setStep('category');
if (letterRequest.title.trim() !== '' && letterRequest.content.trim() !== '') {
if (randomMatched) {
console.log('랜덤편지 답장 전송용API');
} else {
postLetter(letterRequest, () => {
console.log(letterRequest);
console.log(prevLetter);
setSend(true);
setStep('category');
});
}
} else {
alert('편지 제목, 내용이 작성되었는지 확인해주세요');
}
Expand All @@ -51,7 +71,7 @@ export default function LetterEditor({
<WritePageButton
text="다음 단계"
onClick={() => {
if (letterTitle.trim() !== '' && letterText.trim() !== '') {
if (letterRequest.title.trim() !== '' && letterRequest.content.trim() !== '') {
setStep('category');
} else {
alert('편지 제목, 내용이 작성되었는지 확인해주세요');
Expand All @@ -67,23 +87,22 @@ export default function LetterEditor({
placeholder="제목을 입력해주세요."
className="body-sb placeholder:text-gray-40 placeholder:border-0"
onChange={(e) => {
setLetterTitle(e.target.value);
setLetterRequest({ title: e.target.value });
}}
value={letterTitle}
value={letterRequest.title}
/>
</div>
<div className="mt-9 flex grow">
<textarea
className={twMerge(
`body-r basic-theme min-h-full w-full px-6`,
`${FONT_TYPE_OBJ[fontType]}`,
`${FONT_TYPE_OBJ[letterRequest.fontType]}`,
)}
placeholder="클릭해서 내용을 작성하세요"
onChange={(e) => {
handleResizeHeight();
setLetterText(e.target.value);
setLetterRequest({ ...letterRequest, content: e.target.value });
}}
value={letterText}
value={letterRequest.content}
></textarea>
</div>
</div>
Expand Down
12 changes: 12 additions & 0 deletions src/pages/Write/OptionSlide.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ function OptionSlide({ prevLetter }: { prevLetter: PrevLetter[] }) {
const optionRef = useRef<HTMLDivElement>(null);

useEffect(() => {
const handleOutsideClick = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (target && !slideRef.current?.contains(target)) {
setSlideActive(false);
}
};
document.body.addEventListener('click', handleOutsideClick);

const handleSlideButton = () => {
// ref가 처음 높이를 못 받아오는거 같아서 비동기로 후처리함
if (slideRef.current) {
Expand All @@ -25,6 +33,10 @@ function OptionSlide({ prevLetter }: { prevLetter: PrevLetter[] }) {
}
};
handleSlideButton();

return () => {
document.body.removeEventListener('click', handleOutsideClick);
};
}, [slideActive]);

return (
Expand Down
Loading