Skip to content

Commit

Permalink
feat : 게시글 수정 관련 코드 작성
Browse files Browse the repository at this point in the history
 - 게시글 수정 버튼을 클릭하면, state의 mode를 변경하는 방식으로 설정.같은 /posting 경로에서 State를 create모드와 modify 모드로 분리.
 - 게시글 수정 시 postId를 기반으로 postData를 호출해오는 API 함수 getPostById 작성
-Posting.jsx 에서 게시글을 수정하는 useEffect작성

ref : #18
  • Loading branch information
minseoKim-11 committed Nov 12, 2024
1 parent a7ade43 commit 13267ae
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 47 deletions.
3 changes: 2 additions & 1 deletion src/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
signupCEOAPI,
} from "./signupAPI";
import { loginAPI } from "./loginAPI";
import{ postJobPosting, updateJobPosting } from "./postingAPI";
import{ postJobPosting, updateJobPosting, getPostById } from "./postingAPI";
import { postListAPI, searchPostListAPI } from "./homeAPI";

export {
Expand All @@ -16,6 +16,7 @@ export {
loginAPI, // 로그인 API
postJobPosting, //모집글 작성 API
updateJobPosting, //모집글 수정 API
getPostById, // 모집글 수정시 postData 불러오기 API
postListAPI, // 알바리스트 불러오기(홈) API
searchPostListAPI, // 알바리스트 불러오기 (검색) API
};
30 changes: 22 additions & 8 deletions src/api/postingAPI.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import axios from "axios";
import { privateAxios } from "../utils/customAxios";

/*---- 게시글 등록 ----*/
Expand All @@ -9,8 +10,7 @@ export const postJobPosting = async (accessToken, payload) => {
};

try {
const result = await privateAxios(accessToken).patch("/api/v1/post", payload);

const result = await privateAxios(accessToken).post("/api/v1/post", payload); // POST로 변경
if (result.status === 200) {
response.isSuccess = true;
response.message = result.data.message;
Expand All @@ -19,18 +19,17 @@ export const postJobPosting = async (accessToken, payload) => {
} catch (err) {
response.isSuccess = false;
response.message = err.response?.data?.message || err.message;

if (err.response?.status === 401) {
alert("인증이 필요합니다. 다시 로그인해주세요.");
}

}

return response;
};

// /*---- 게시글 수정 ----*/
export const updateJobPosting = async (accessToken, postId, postData) => {
/*---- 게시글 수정 ----*/
export const updateJobPosting = async (accessToken, postId, postData, userId) => {
const response = {
isSuccess: false,
message: "",
Expand All @@ -39,11 +38,11 @@ export const updateJobPosting = async (accessToken, postId, postData) => {

try {
const body = {
postId,
postId,
userId,
storeName: "", // 수정 불가
workPlaceAddress: "", // 수정 불가
postData, // 수정 가능한 postData만 포함
postData,
};

const result = await privateAxios(accessToken).patch(`/api/v1/post/${postId}`, body);
Expand All @@ -59,4 +58,19 @@ export const updateJobPosting = async (accessToken, postId, postData) => {
}

return response;
};

/*---- 게시글 데이터 호출 ----*/
export const getPostById = async (postId, accessToken) => {
try {
const response = await axios.get(`http://43.203.223.82:8080/api/v1/post/${postId}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});
return response.data;
} catch (error) {
console.error("Error fetching post data:", error);
throw error;
}
};
4 changes: 2 additions & 2 deletions src/components/ButtonsModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,14 @@ const ButtonsModal = ({ isMode, setIsMode, postId }) => {
//게시글 수정
const modifyPosts = () => {
if (confirm("해당 게시글을 수정하시겠습니까?")) {
navigate(`/modify`, {
navigate("/posting", {
state: {
postId: postId,
mode: "modify", // 수정 모드 전달
},
});
}
};
};

// 게시글 삭제
const deletePosts = () => {
Expand Down
72 changes: 62 additions & 10 deletions src/pages/recruitment/Posting.jsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { PageContainer, ContentContainer, FixedButtonContainer } from "../../styles/posting/PostingStyles";
import { InputField, Tag, Toggle, WeekdayPicker, WorkTimePicker, PayPicker, AddressInput, PhotoUpload, DescriptionInput, PhoneInput, Button } from "../../components";
import "../../styles/posting/Posting.css";
import { POSTING_UPMU_TAG } from "../../constants";
import { postJobPosting, updateJobPosting } from "../../api";
import { postJobPosting, updateJobPosting, getPostById } from "../../api";
import { useNavigate, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import getAccessToken from "../../utils/getAccessToken"; // 일반 함수로 가져오기
import getAccessToken from "../../utils/getAccessToken"; // 일반 함수로 가져와야 오류 안뜸!!
import { createPayload } from "../../utils/posting/payloadHelper"; // 분리된 payload 생성 함수
import { validateForm } from "../../utils/posting/validationHelper"; // 분리된 유효성 검증 함수
import { parseAddress, convertDays } from "../../utils/posting/formatHelper"; // 분리된 주소 및 요일 변환 함수

const Posting = () => {
const state = useSelector((state) => state);
const accessToken = getAccessToken(state);
const location = useLocation();
const navigate = useNavigate();
const userId = useSelector((state) => state.userInfo.userId);
const { mode, postId } = location.state || { mode: "create", postId: null };

const [isOptionSelected, setIsOptionSelected] = useState(false);
const [validStates, setValidStates] = useState({
title: true,
Expand All @@ -36,12 +41,6 @@ const Posting = () => {
workPeriod: "1개월 이상"
});

const location = useLocation();
const navigate = useNavigate();
const mode = location.state?.mode || "create";
const postId = location.state?.postId || null;
const userId = useSelector((state) => state.userInfo.userId);

const handleChange = (key, value) => {
setFormData((prev) => ({ ...prev, [key]: value }));
};
Expand All @@ -59,6 +58,59 @@ const Posting = () => {
handleChange("selectedOption", value);
setIsOptionSelected(true);
};
// 게시글 수정 useEffect
useEffect(() => {
if (mode === "modify" && postId) {
// 수정 모드에서 데이터 가져오기
fetchPostData(postId);
}
}, [mode, postId]);

const fetchPostData = async (postId) => {
try {
const postData = await getPostById(postId, accessToken);
populateFormData(postData); // 폼 데이터 초기화
} catch (error) {
alert("게시글 데이터를 불러오는 데 실패했습니다.");
}
};

const populateFormData = (postData) => {
const {
title,
workType,
pay,
payType,
workStartHour,
workStartMinute,
workEndHour,
workEndTimeMinute,
isNegotiable,
applyNumber,
workDays,
content,
doName,
siName,
detailName,
} = postData.postData;

setFormData({
...formData,
title,
workTags: [workType],
workDays,
workTime: {
start: `${workStartHour}:${workStartMinute.toString().padStart(2, "0")}`,
end: `${workEndHour}:${workEndTimeMinute.toString().padStart(2, "0")}`,
},
pay,
payType,
isNegotiable,
applyNumber,
description: content,
workLocation: `${doName} ${siName} ${detailName}`, // 주소 결합
});
};

const handleSubmit = async () => {
const allValid = Object.values(validStates).every((isValid) => isValid);
Expand Down Expand Up @@ -95,7 +147,7 @@ const Posting = () => {
return (
<PageContainer>
<ContentContainer>
<div className="header">어떤 알바를 구하고 계신가요?</div>
<div className="header">{mode === "modify" ? "게시글 수정" : "어떤 알바를 구하고 계신가요?"}</div>
<div className="toggle-section">
<Toggle
options={["업무 목적"]}
Expand Down
55 changes: 29 additions & 26 deletions src/utils/posting/validationHelper.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
// utils/validationHelper.js
export const validateForm = (payload, formData) => {
const requiredFields = {
"제목": payload.postData.title,
"하는 일": payload.postData.workType,
"일하는 기간": formData.workPeriod,
"일하는 요일": formData.workDays,
"일하는 시간": formData.workTime?.start && formData.workTime?.end,
"급여": formData.pay,
"일하는 장소": formData.workLocation,
"업체명": payload.storeName,
"연락처": payload.postData.applyNumber,
};

for (const [label, value] of Object.entries(requiredFields)) {
if (
value === undefined ||
value === null ||
(typeof value === "string" && value.trim() === "") ||
(Array.isArray(value) && value.length === 0) ||
value === false
) {
alert(`${label}을(를) 입력해주세요.`);
return false;
}
}
return true;
};
const requiredFields = {
"제목": payload.postData.title,
"하는 일": payload.postData.workType,
"일하는 기간": formData.workPeriod,
"일하는 요일": formData.workDays,
"일하는 시간": formData.workTime?.start && formData.workTime?.end,
"급여": formData.pay,
"일하는 장소": formData.workLocation,
"업체명": payload.storeName,
"연락처": payload.postData.applyNumber,
};

const missingFields = Object.entries(requiredFields)
.filter(([_, value]) =>
value === undefined ||
value === null ||
(typeof value === "string" && value.trim() === "") ||
(Array.isArray(value) && value.length === 0) ||
value === false
)
.map(([label]) => label);

if (missingFields.length > 0) {
alert(`다음 항목을 입력해주세요: ${missingFields.join(", ")}`);
return false; // 유효성 검증 실패
}

return true; // 유효성 검증 성공
};

0 comments on commit 13267ae

Please sign in to comment.