Skip to content

Commit

Permalink
Merge pull request #62 from LikeLionHGU/jonghyun_feat/#61
Browse files Browse the repository at this point in the history
feat: 일지 작성 API 연결 및 경로 설정 완료
  • Loading branch information
dkrehd0519 authored Aug 2, 2024
2 parents 387854e + a40177b commit b54ffe6
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 50 deletions.
26 changes: 26 additions & 0 deletions src/apis/createDiary.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import axios from "axios";

const createDiary = async (formDataToSend, csrfToken, goalId) => {
console.log("API 코드에서 잘 넘어왔는지", formDataToSend, csrfToken, goalId);
try {
const serverResponse = await axios.post(
`${process.env.REACT_APP_HOST_URL}/v1/goals/${goalId}/journals`,
formDataToSend,
{
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": csrfToken,
},
}
);
console.log("일지가 정상적으로 추가되었음", serverResponse);

return serverResponse.data;
} catch (error) {
console.error("일지 추가 실패:", error);
throw error;
}
};

export default createDiary;
22 changes: 6 additions & 16 deletions src/diaryListPage/components/CreateDiaryModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from "react";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
function CreateDiaryModal({ setIsModalOpen }) {
function CreateDiaryModal({ setIsModalOpen, goalId }) {
const navigate = useNavigate();

const closeCreateDiaryModal = () => {
Expand All @@ -25,27 +25,17 @@ function CreateDiaryModal({ setIsModalOpen }) {
<TextContainer>
<MainText>👾 (봇이름)이와 함께 일지 작성하기</MainText>
<SubText>
<div>
무슨 일지를 써야할지 고민이 되는 날에도, 고된 일정으로
피곤한 하루에도
</div>{" "}
<div style={{ marginTop: "3px" }}>
(봇이름)이가 chicky님의 꾸준한 기록을 도와줄게요!
</div>
<div>무슨 일지를 써야할지 고민이 되는 날에도, 고된 일정으로 피곤한 하루에도</div>{" "}
<div style={{ marginTop: "3px" }}>(봇이름)이가 chicky님의 꾸준한 기록을 도와줄게요!</div>
</SubText>
</TextContainer>
</WriteMethod>
<WriteMethod onClick={() => navigate("/write")}>
<WriteMethod onClick={() => navigate(`/write?id=${goalId}`)}>
<TextContainer>
<MainText>✍️ 직접 작성하기</MainText>
<SubText>
<div>
오늘만큼은 적고 싶은게 너무 많은 날, 떠오르는 생각과 느낌을
적고 싶은 날
</div>
<div style={{ marginTop: "3px" }}>
자유롭게 하루의 일지를 적어보아요!
</div>
<div>오늘만큼은 적고 싶은게 너무 많은 날, 떠오르는 생각과 느낌을 적고 싶은 날</div>
<div style={{ marginTop: "3px" }}>자유롭게 하루의 일지를 적어보아요!</div>
</SubText>
</TextContainer>
</WriteMethod>
Expand Down
24 changes: 6 additions & 18 deletions src/diaryListPage/components/Diaries.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,9 @@ function Diaries() {
let diaries = goalList.journals;

if (currentSort === "최신순") {
diaries = diaries.sort(
(a, b) => new Date(b.createdDate) - new Date(a.createdDate)
);
diaries = diaries.sort((a, b) => new Date(b.createdDate) - new Date(a.createdDate));
} else if (currentSort === "오래된 순") {
diaries = diaries.sort(
(a, b) => new Date(a.createdDate) - new Date(b.createdDate)
);
diaries = diaries.sort((a, b) => new Date(a.createdDate) - new Date(b.createdDate));
}

return diaries;
Expand All @@ -64,20 +60,14 @@ function Diaries() {
<ListPart>
<Searchbar>
<SearchIcon />
<input
className="search-bar"
placeholder="제목+내용을 입력해보세요."
></input>
<input className="search-bar" placeholder="제목+내용을 입력해보세요."></input>
</Searchbar>
<DairyListBox>
<div className="diary-list-head">
<div onClick={openCreateDiaryModal} className="diary-add">
일지 추가하기 <img src={goPencil} alt="" />
</div>
<DiaryViewDropdown
currentSort={currentSort}
setCurrentSort={setCurrentSort}
/>
<DiaryViewDropdown currentSort={currentSort} setCurrentSort={setCurrentSort} />
</div>
<DiaryList>
{filteredDiaries.map((diaries, index) => (
Expand All @@ -89,15 +79,13 @@ function Diaries() {
</div>
</div>
{diaries.thumbnail ? ( // 이미지url이 있는지 없는지 판별, 있으면 Image 컴포넌트 보여주고 없으면 안넣음
<Image
style={{ backgroundImage: `url(${diaries.thumbnail})` }}
/>
<Image style={{ backgroundImage: `url(${diaries.thumbnail})` }} />
) : null}
</Diary>
))}
</DiaryList>
</DairyListBox>
{isModalOpen && <CreateDiaryModal setIsModalOpen={setIsModalOpen} />}
{isModalOpen && <CreateDiaryModal setIsModalOpen={setIsModalOpen} goalId={goalId} />}
</ListPart>
);
}
Expand Down
4 changes: 2 additions & 2 deletions src/diaryWritePage/components/DiaryPostModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import React from "react";
import styled from "styled-components";
import fire from "../../asset/emoji/fire.png";
import { useNavigate } from "react-router-dom";
function DiaryPostModal({ setPostedModal }) {
function DiaryPostModal({ setPostedModal, goalId }) {
const navigate = useNavigate();
const closeModal = () => {
setPostedModal(false);
navigate("/homepage"); // !!!! 중요, 나중에 연결할때 이 부분이 diaryList?id= 링크로 연결되어야함.
navigate(`/diaryList?id=${goalId}`); // !!!! 중요, 나중에 연결할때 이 부분이 diaryList?id= 링크로 연결되어야함.
};

return (
Expand Down
11 changes: 8 additions & 3 deletions src/diaryWritePage/components/DiaryWrite.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ThumbnailModal from "./ThumbnailModal";
import DiaryPostModal from "./DiaryPostModal";
import { useRecoilValue } from "recoil";
import { tokenState } from "../../atom/atom";
import { useLocation } from "react-router-dom";
function DiaryWrite() {
const [thumbnailModal, setThumbnailModal] = useState(false); // 썸네일 사진 추가하는 모달
const [postedModal, setPostedModal] = useState(false); //일지가 추가되었다는 걸 알려주는 모달
Expand All @@ -13,6 +14,9 @@ function DiaryWrite() {
content: "",
});
const csrfToken = useRecoilValue(tokenState);
const location = useLocation();
const queryParams = new URLSearchParams(location.search);
const goalId = queryParams.get("id");

const openThumbnailModal = () => {
setThumbnailModal(true);
Expand Down Expand Up @@ -60,11 +64,12 @@ function DiaryWrite() {
<ThumbnailModal
setThumbnailModal={setThumbnailModal}
setPostedModal={setPostedModal}
formData={formData}
goalId={goalId}
csrfToken={csrfToken}
/>
)}
{!thumbnailModal && postedModal && (
<DiaryPostModal setPostedModal={setPostedModal} />
)}
{!thumbnailModal && postedModal && <DiaryPostModal setPostedModal={setPostedModal} goalId={goalId} />}
</BoxWrapper>
</Wrapper>
);
Expand Down
33 changes: 22 additions & 11 deletions src/diaryWritePage/components/ThumbnailModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import React, { useEffect, useRef, useState } from "react";
import styled from "styled-components";
import CloseRoundedIcon from "@mui/icons-material/CloseRounded";
import AddRoundedIcon from "@mui/icons-material/AddRounded";
function ThumbnailModal({ setThumbnailModal, setPostedModal }) {
import createDiary from "../../apis/createDiary";
function ThumbnailModal({ setThumbnailModal, setPostedModal, formData, goalId, csrfToken }) {
// 이미지 설정//
const fileInputRef = useRef(null);
const [previewUrl, setPreviewUrl] = useState(null); // 미리보기창에 들어갈 이미지 url
Expand All @@ -15,13 +16,28 @@ function ThumbnailModal({ setThumbnailModal, setPostedModal }) {
const handleImageUploadClick = () => {
fileInputRef.current.click();
};
const handleNextStep = () => {
const handleNextStep = async () => {
// 대표사진 선택하기 모달에서 "다음으로" 버튼 누르고 나면 사진선택 모달은 숨기고 그 이후 모달(일지 추가 완료 모달)을 보여줘야함.
// *** 이 함수 안에서 일지를 백엔드로 submit해야할듯 (내용 + 대표사진) *** //
// 일단 임시로 "다음으로"버튼 누르면 그 다음 모달로 넘어가는 것만 해둠.

setThumbnailModal(false);
setPostedModal(true);
// 아직 이미지는 보내는거 연결안했는데 백엔드 구현되면 수정해야함
try {
const { title, content } = formData;

const formDataToSend = new FormData();
formDataToSend.append("title", title);
formDataToSend.append("content", content);

// 이미지 파일이 존재할 경우에만 추가
if (fileInputRef.current.files[0]) {
formDataToSend.append("image", fileInputRef.current.files[0]);
}
await createDiary(formDataToSend, csrfToken, goalId);
setThumbnailModal(false);
setPostedModal(true);
} catch (error) {
console.error("일지 생성 실패", error);
}
};
const handleFileInputChange = (event) => {
const file = event.target.files[0];
Expand Down Expand Up @@ -67,12 +83,7 @@ function ThumbnailModal({ setThumbnailModal, setPostedModal }) {
<div className="image-add-text">사진 추가하기</div>
</>
)}
<input
type="file"
style={{ display: "none" }}
onChange={handleFileInputChange}
ref={fileInputRef}
/>
<input type="file" style={{ display: "none" }} onChange={handleFileInputChange} ref={fileInputRef} />
</ImageAdd>
<Buttons>
<NextBtn>
Expand Down

0 comments on commit b54ffe6

Please sign in to comment.