Skip to content

Commit

Permalink
fix : 게시글 수정 관련 컴포넌트 수정
Browse files Browse the repository at this point in the history
- 게시글 수정 버튼을 눌렀을 때 value 값이 전달되지 않는 부분을 해결하기 위해 각 컴포넌트들에 useEffect() 사용하여 vlaue값 넣어두는 작업 진행 예정
- 현재 InputField부터 수정 완료, 다른 컴포넌트들도 같은 방식으로 수정 예정

ref : #18
  • Loading branch information
minseoKim-11 committed Nov 13, 2024
1 parent 4786761 commit ad84854
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 86 deletions.
13 changes: 6 additions & 7 deletions src/api/postingAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ export const updateJobPosting = async (
response.data = result.data.data;
}
} catch (err) {
response.isSuccess = false;
response.message = err.response.data;
console.error("Error in updateJobPosting:", err);
response.message = err.response?.data?.message || "Unknown error occurred.";
}

return response;
Expand All @@ -73,17 +73,16 @@ export const getPostById = async (postId, accessToken) => {
data: null,
};
try {
const result = await privateAxios(accessToken).get(
`/api/v1/post/${postId}`
);
const result = await privateAxios(accessToken).get(`/api/v1/post/${postId}`);
if (result.status === 200) {
response.isSuccess = true;
response.message = result.data.message;
response.message = "Post data fetched successfully.";
response.data = result.data;
}
} catch (error) {
console.error("Error fetching post data:", error);
response.message = error.response.data;
response.message =
error.response?.data?.message || "Failed to fetch post data.";
}
return response;
};
Expand Down
13 changes: 8 additions & 5 deletions src/components/posting/InputField.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { useState } from "react";
import React, { useState,useEffect } from "react";
import { InputWrapper, StyledLabel, BasicInput, ErrorMessage } from "../../styles/posting/InputFieldStyles";

const InputField = ({
label,
value,
placeholder,
color = "#ffffff",
textColor = "#333",
Expand All @@ -12,14 +13,16 @@ const InputField = ({
onValidityChange, // 유효성 상태 전달 콜백
minLength = 6,
}) => {
const [inputValue, setInputValue] = useState("");
const [inputValue, setInputValue] = useState(value || ""); // 초기값 설정
useEffect(() => {
setInputValue(value); // 외부에서 value가 변경되면 반영
}, [value]);

const isValid = label !== "제목" || (inputValue.length >= minLength && inputValue.length <= 30);

const handleChange = (e) => {
const value = e.target.value;
setInputValue(value);
onChange && onChange(value);
setInputValue(e.target.value);
onChange && onChange(e.target.value);
onValidityChange && onValidityChange(isValid); // 유효성 상태 전달
};

Expand Down
2 changes: 1 addition & 1 deletion src/components/posting/PhotoUpload.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { uploadPostImageAPI } from "../../api";
import getAccessToken from "../../utils/getAccessToken";
import { useDispatch } from "react-redux";

const PhotoUpload = ({ label, selectedPhotos, setSelectedPhotos }) => {
const PhotoUpload = ({ label, selectedPhotos=[], setSelectedPhotos }) => {
const accessToken = getAccessToken();
const dispatch = useDispatch();

Expand Down
166 changes: 93 additions & 73 deletions src/pages/recruitment/Posting.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ const Posting = () => {
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,
description: true,
Expand Down Expand Up @@ -71,10 +70,10 @@ const Posting = () => {
handleChange("isNumberPublic", !noCalls);
};

const handleToggleClick = (value) => {
handleChange("selectedOption", value);
setIsOptionSelected(true);
};
// const handleToggleClick = (value) => {
// handleChange("selectedOption", value);
// setIsOptionSelected(true);
// };
// 게시글 수정 useEffect
useEffect(() => {
if (mode === "modify" && postId) {
Expand All @@ -83,15 +82,22 @@ const Posting = () => {
}, [mode, postId]);

const fetchPostData = async (postId) => {
try {
const postData = await getPostById(postId, accessToken);
populateFormData(postData); // 폼 데이터 초기화
} catch (error) {
alert("게시글 데이터를 불러오는 데 실패했습니다.");
const response = await getPostById(postId, accessToken);
console.log("Fetched post data:", response);
if (response.isSuccess) {
populateFormData(response.data);
} else {
alert(`데이터 호출 실패: ${response.message}`);
}
};
};

const populateFormData = (postData) => {
if (!postData || !postData.data || !postData.data.postData) {
console.error("Invalid postData structure:", postData);
alert("게시글 데이터를 불러오는 데 실패했습니다.");
return; // 함수 실행 중단
}

const {
title,
workType,
Expand All @@ -108,98 +114,114 @@ const Posting = () => {
doName,
siName,
detailName,
} = postData.postData;

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

const handleSubmit = () => {
};
const handleSubmit = async () => {
const allValid = Object.values(validStates).every((isValid) => isValid);
if (!allValid) {
alert("모든 필드를 올바르게 입력해주세요.");
return;
}
const payload = createPayload(
formData,
postId,
userId,
parseAddress,
convertDays
);


const payload = createPayload(formData, postId, userId, parseAddress, convertDays);

if (!validateForm(payload, formData)) {
alert("모든 필드를 올바르게 입력해주세요.");
return;
}

try {
if (mode !== "modify") {
postJobPosting(accessToken, dispatch, payload).then((res) => {
if (res.isSuccess) {
alert("게시글이 성공적으로 등록되었습니다.");
navigate("/home");
} else {
alert(res.message);
}
});
const response = mode === "create"
? await postJobPosting(accessToken, dispatch, payload)
: await updateJobPosting(accessToken, postId, payload.postData, userId);

if (response.isSuccess) {
alert(mode === "create" ? "게시글이 성공적으로 등록되었습니다." : "게시글이 성공적으로 수정되었습니다.");
navigate("/home");
} else {
updateJobPosting(accessToken, postId, postData, userId).then((res) => {
if (res.isSuccess) {
alert("게시글이 성공적으로 수정되었습니다.");
navigate("/home");
} else {
alert(res.message);
}
});
alert(`오류: ${response.message}`);
}
} catch (error) {
console.error("Submission error:", error);
alert("제출 과정에서 오류가 발생했습니다. 다시 시도해주세요.");
}
};

// const handleSubmit = () => {
// const allValid = Object.values(validStates).every((isValid) => isValid);
// if (!allValid) {
// alert("모든 필드를 올바르게 입력해주세요.");
// return;
// }
// const payload = createPayload(
// formData,
// postId,
// userId,
// parseAddress,
// convertDays
// );

// if (!validateForm(payload, formData)) {
// return;
// }

// try {
// if (mode !== "modify") {
// postJobPosting(accessToken, dispatch, payload).then((res) => {
// if (res.isSuccess) {
// alert("게시글이 성공적으로 등록되었습니다.");
// navigate("/home");
// } else {
// alert(res.message);
// }
// });
// } else {
// updateJobPosting(accessToken, postId, postData, userId).then((res) => {
// if (res.isSuccess) {
// alert("게시글이 성공적으로 수정되었습니다.");
// navigate("/home");
// } else {
// alert(res.message);
// }
// });
// }
// } catch (error) {
// alert("제출 과정에서 오류가 발생했습니다. 다시 시도해주세요.");
// }
// };
return (
<PageContainer>
<ContentContainer>
<div className="header">
{mode === "modify" ? "게시글 수정" : "어떤 알바를 구하고 계신가요?"}
</div>
<div className="toggle-section">
<Toggle
options={["업무 목적"]}
selectedOption={formData.selectedOption}
onChange={handleToggleClick}
styleType="card"
/>
</div>
{isOptionSelected && (
<>
<div className="form-section">
<InputField
label="제목"
placeholder="공고 내용을 요약해주세요."
onChange={(value) => handleChange("title", value)}
onValidityChange={(isValid) =>
handleValidityChange("title", isValid)
}
/>
</div>
<div className="form-section">
<>
<div className="form-section">
<InputField
label="제목"
placeholder="공고 내용을 요약해주세요."
value={formData.title}
onChange={(value) => handleChange("title", value)}
onValidityChange={(isValid) => handleValidityChange("title", isValid)}
/>
</div>
<div className="form-section">
<Tag
label="하는 일"
tags={POSTING_UPMU_TAG}
Expand Down Expand Up @@ -244,15 +266,13 @@ const Posting = () => {
}}
/>
</div>
<div className="form-section">
<PhotoUpload
<PhotoUpload
label="사진"
selectedPhotos={formData.imageUrlList}
setSelectedPhotos={(photos) =>
handleChange("imageUrlList", photos)
}
/>
</div>
<div className="form-section">
<DescriptionInput
label="자세한 설명"
Expand Down Expand Up @@ -282,8 +302,8 @@ const Posting = () => {
}
/>
</div>
</>
)}
</>

</ContentContainer>
<FixedButtonContainer>
<Button
Expand Down

0 comments on commit ad84854

Please sign in to comment.