Skip to content

Commit

Permalink
feat(#5):캘린더 하는중
Browse files Browse the repository at this point in the history
  • Loading branch information
EunSeok-222 committed Nov 6, 2024
1 parent 84af9fc commit 9e26997
Show file tree
Hide file tree
Showing 9 changed files with 194 additions and 175 deletions.
2 changes: 2 additions & 0 deletions src/apis/AxiosInstance.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const token = tokenString ? JSON.parse(tokenString) : null;
const Axios = axios.create({
// eslint-disable-next-line no-undef
baseURL: import.meta.env.VITE_BASE_URL,
// baseURL: "http://localhost:8080/api", // Replace with your actual API URL
// eslint-disable-next-line no-undef
headers: {
Authorization: `Bearer ${token?.loginState?.data?.accessToken}`,
"Content-Type": "application/json",
Expand Down
51 changes: 27 additions & 24 deletions src/pages/CommunityPage/CommunityDetail.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ const CommunityDetail = () => {
const { no } = useParams(); // %% URL에서 글 번호(no)를 가져옴 %%
const [postDetail, setPostDetail] = useState([]);
const [comments, setComments] = useState([]);
const [refreshComments, setRefreshComments] = useState(false);

useEffect(() => {
// 상세정보 불러오기

axios
.get(`/communities/${no}`)
.get(`https://ureca.store/api/communities/${no}`)
.then(response => {
setPostDetail(response.data);
console.log('나눔 상세 :', response.data);
Expand All @@ -24,49 +23,51 @@ const CommunityDetail = () => {
console.error('Error fetching data:', error);
});
}, [no]);
// 댓글 목록 불러오기
useEffect(( ) => {
const fetchComments = async () => {
try {
const response = await axios.get(`https://ureca.store/api/communityComments`);
setComments(response.data); // 댓글 목록 갱신
console.log('댓글 목록 :', response.data);
} catch (error) {
console.error('Error:', error);
}
};

fetchComments();
}, [refreshComments]);

useEffect(() => {
axios
.get(`/communityComments`)
.then(response => {
setComments(response.data);
console.log('댓글 목록 :', response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
}, []);

// 좋아요 수 증가 함수
const good = () => {
const updatedGood = postDetail.good + 1;

// 서버의 좋아요 수 업데이트 요청
axios
.put(`/communities/${no}`, { ...postDetail, good: updatedGood })
.put(`https://ureca.store/api/communities/${no}`, { ...postDetail, good: updatedGood })
.then(response => {
console.log('좋아요 업데이트:', response.data);
setPostDetail(prevDetail => ({ ...prevDetail, good: updatedGood }));
})
.catch(error => {
console.error('좋아요 업데이트 실패:', error);
});
};
}
//댓글 등록
const handleSubmit = e => {
e.preventDefault(); // 새로고침 방지
const formData = new FormData(e.target);
const user = localStorage.getItem('userId');
const data = Object.fromEntries(formData.entries()); //객체로 변환
// const now = new Date().toISOString();
// data.createdAt = now; // 현재 시간 추가
data.post = no;
//글 등록
data.user = user;
axios
.post('/communityComments', data)
.post('https://ureca.store/api/communityComments', data)
.then(response => {
console.log('등록 : ', response.data);
setComments(prevComments => [...prevComments, response.data]);
console.log('등록 data : ', data);
alert('댓글이 등록되었습니다!');
setRefreshComments(prev => !prev);
})
.catch(error => console.error('오류 발생:', error));

Expand All @@ -76,7 +77,7 @@ const CommunityDetail = () => {
return (
<Container>
<ItemTitle>
<ListImg src={`/${postDetail.imageUrl}`} alt={postDetail.imageUrl} />
<ListImg src={postDetail.imageUrl} alt={postDetail.imageUrl} />
<ImgBt>
<ImgNo>1 / 5</ImgNo>
</ImgBt>
Expand Down Expand Up @@ -122,7 +123,6 @@ const CommunityDetail = () => {
</CommentST>
</ItemTitle>
<CommentFrom onSubmit={handleSubmit}>
<input type="number" name="user" placeholder="유저번호" required />
<CommentCC type="text" name="comment" placeholder="댓글을 달아주세요." required />
<CommentSubmit type="submit">등록</CommentSubmit>
</CommentFrom>
Expand Down Expand Up @@ -248,15 +248,18 @@ const CommentST = styled.div`
`;
const CommentFrom = styled.form`
width: 100%;
position: absolute;
display: flex;
justify-content: flex-end;
bottom: 0px;
margin-top: auto;
margin-bottom: 64px;
`;
const Container = styled.div`
height: 100dvh;
display: flex;
flex-direction: column;
position: relative;
`;
const CommentCC = styled.input`
height: 40px;
Expand Down
8 changes: 4 additions & 4 deletions src/pages/CommunityPage/CommunityList.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const CommunityList = () => {

useEffect(() => {
axios
.get('/communities')
.get('https://ureca.store/api/communities')
.then(response => {
setComunityList(response.data); // 응답 데이터 저장
console.log('게시글 목록:', response.data);
Expand All @@ -39,7 +39,7 @@ const CommunityList = () => {
const updatedGood = (item.good || 0) + 1;
// 서버의 좋아요 수 업데이트 요청
axios
.put(`/communities/${postId}`, { ...item, good: updatedGood })
.put(`https://ureca.store/api/communities/${postId}`, { ...item, good: updatedGood })
.then(response => {
console.log('좋아요 업데이트:', response.data);
})
Expand All @@ -56,7 +56,7 @@ const CommunityList = () => {
// 댓글 목록 불러오기
useEffect(() => {
axios
.get(`/communityComments`)
.get(`https://ureca.store/api/communityComments`)
.then(response => {
setComments(response.data);
console.log('댓글 목록 :', response.data);
Expand Down Expand Up @@ -96,7 +96,7 @@ const CommunityList = () => {
e.preventDefault();
navigate(`/community/detail/${item.postId}`);
}}>
<ListImg src={`/${item.imageUrl}`} />
<ListImg src={item.imageUrl}/>
<ListTitlesContainer>
<ListTItle>제목 : {item.title}</ListTItle>
<ListDate>
Expand Down
2 changes: 1 addition & 1 deletion src/pages/CommunityPage/CommunityWrite.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const CommunityWrite = () => {
}

try {
const response = await axios.post('/communities', formData, {
const response = await axios.post('https://ureca.store/api/communities', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
Expand Down
106 changes: 74 additions & 32 deletions src/pages/HealthCare/HealthCare.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,46 +7,90 @@ import styled from "styled-components";
const HealthCare = () => {
const [selectedDate, setSelectedDate] = useState(new Date());
const [appointments, setAppointments] = useState([]);
const [petId, setPetId] = useState();
const [showInput, setShowInput] = useState({
hospital: true,
nextVisit: false,
healthCare: false,
});
const [memo, setMemo] = useState("");
const user = localStorage.getItem('userId');
console.log(user)

const petData = () => {
axios.get(`https://ureca.store/api/pets`)
.then((response) => {
setPetId( user === response.data.userId)
console.log('petId :', response.data);
})
}


useEffect(() => {
const userData = (date) => {
if (!date || isNaN(new Date(date).getTime())) {
return "";
}
return new Date(date).toISOString().split("T")[0];
};





// const = async () => {
// try {
// const response = await axios.get(`https://ureca.store/api/healths`);
// setAppointments(response.data.map(item => ({ ...item, date: new Date(item.date) })));
// console.log('댓글 목록:', response.data);
// } catch (error) {
// console.error("Error fetching data:", error);
// }
// };


}, []);

const handleDateChange = (date) => {
setSelectedDate(date);
};

const addAppointment = async (type, e) => {
setAppointments([...appointments, { date: selectedDate, type, memo }]);
// e.preventDefault(); // 새로고침 방지
const formData = new FormData();
const formattedDate = formatDate(selectedDate);
formData.append("pet", 1);

if (type === "병원 방문일") {
formData.append("visitedDate", formattedDate);
} else if (type === "다음 방문일") {
formData.append("nextCheckupDate", formattedDate);
} else if (type === "건강 관리") {
formData.append("healthDate", formattedDate);
formData.append("notes", memo); // 메모 추가
}
console.log("건강 :", formData);

const userId = localStorage.getItem('userId');

console.log("userId :", userId);
try {
const response = await axios.post("/healths", formData, {
// headers: {
// 'Content-Type': 'application/json'
// },
});
console.log("등록 data : ", response.data);
// petId 가져오기
const response = await axios.get(`https://ureca.store/api/pets/pet/${userId}`);
const petId = response.data[0].petId;
console.log("petId :", petId);

// petId를 포함하여 formData에 추가
formData.append("pet", petId);

// 선택된 타입에 따라 필요한 필드를 formData에 추가
if (type === "병원 방문일") {
formData.append("visitedDate", formattedDate);
} else if (type === "다음 방문일") {
formData.append("nextCheckupDate", formattedDate);
} else if (type === "건강 관리") {
formData.append("healthDate", formattedDate);
formData.append("notes", memo); // 메모 추가
}
console.log("formData 내용:", formData);

// formData를 포함하여 POST 요청 전송
const postResponse = await axios.post("/healths", formData);
console.log("등록 data : ", postResponse.data);
alert("등록 성공");
setMemo("");

} catch (error) {
console.error("오류 발생:", error);
alert("오류 발생:");
alert("오류 발생");
}
};

Expand Down Expand Up @@ -101,16 +145,7 @@ const HealthCare = () => {
}
};

// useEffect(()=>{
// axios.get(`/healths`)
// .then((response) => {
// setAppointments(response.data.map(item => ({ ...item, date: new Date(item.date) })));
// console.log('댓글 목록 :', response.data);
// })
// .catch((error) => {
// console.error("Error fetching data:", error);
// });
// },[]);

return (
<Container>
<Legend>
Expand Down Expand Up @@ -220,7 +255,7 @@ const CalendarWrapper = styled.div`
`;

const StyledCalendar = styled(Calendar)`
width: 100%;
.react-calendar__tile {
padding: 1em 0.5em;
Expand All @@ -235,6 +270,8 @@ const StyledCalendar = styled(Calendar)`
.react-calendar__tile--active {
background-color: #fff3e8;
color: black;
height: 5px;
width: 5px;
}
.calendar-tile {
Expand All @@ -247,6 +284,10 @@ const StyledCalendar = styled(Calendar)`
border-radius: 8px;
}
.react-calendar__month-view__days__day--weekend {
color: #17a1fa;
}
.selected {
background-color: #fff3e8;
}
Expand Down Expand Up @@ -334,7 +375,8 @@ const RegisterButton = styled(Button)`
margin-left: 5px;
&:hover {
background-color: #45a049;
background-color: #ec7a4f;
color: wheat;
}
`;

Expand Down
Loading

0 comments on commit 9e26997

Please sign in to comment.