-
- 욕설 광고등 운영저책 위반 시 제재를 받으실 수 있습니다
-
- {loading ? '등록중...' : '작성 완료'}
-
-
+
+
+ 욕설 광고등 운영저책 위반 시 제재를 받으실 수 있습니다
+
+ {loading ? "등록중..." : "작성 완료"}
+
+
@@ -196,7 +209,7 @@ const CategoryBtn = styled.div`
display: flex;
flex-direction: column;
align-items: center;
- opacity: ${({ $active }) => ($active ? '1' : '0.5')};
+ opacity: ${({ $active }) => ($active ? "1" : "0.5")};
transition: opacity 0.3s;
cursor: pointer;
&:hover {
@@ -287,7 +300,7 @@ const Form = styled.form`
`;
const SubmitBtn = styled.div`
position: absolute;
- bottom:0px;
+ bottom: 0px;
width: 100%;
justify-content: flex-end;
`;
diff --git a/src/pages/MyPage/MyPage.jsx b/src/pages/MyPage/MyPage.jsx
index 9d8fce1..baabb43 100644
--- a/src/pages/MyPage/MyPage.jsx
+++ b/src/pages/MyPage/MyPage.jsx
@@ -1,12 +1,22 @@
-import React, { useState, useEffect, useRef } from 'react';
-import { RxAvatar } from 'react-icons/rx';
-import { MdOutlineKeyboardArrowRight, MdOutlineArrowBack, MdOutlineArrowForward } from 'react-icons/md';
-import styled from 'styled-components';
-import { useNavigate } from 'react-router-dom';
-import axios from '../../apis/AxiosInstance';
-import { images } from '../../components/Images';
-import user from './user.png'
-import { ScrollableContainer, Container, MainContainer, UserInfo, EditButton } from './Sytles/MyPage';
+import React, { useState, useEffect, useRef } from "react";
+import { RxAvatar } from "react-icons/rx";
+import {
+ MdOutlineKeyboardArrowRight,
+ MdOutlineArrowBack,
+ MdOutlineArrowForward,
+} from "react-icons/md";
+import styled from "styled-components";
+import { useNavigate } from "react-router-dom";
+import axios from "../../apis/AxiosInstance";
+import { images } from "../../components/Images";
+import user from "./user.png";
+import {
+ ScrollableContainer,
+ Container,
+ MainContainer,
+ UserInfo,
+ EditButton,
+} from "./Sytles/MyPage";
const SubContainer = styled.div`
display: flex;
@@ -95,7 +105,7 @@ const Coupon = styled.span`
`;
const ActivePetName = styled.p`
- margin-top:10px;
+ margin-top: 10px;
font-size: 15px;
font-weight: bold;
color: #ff6e00;
@@ -157,7 +167,7 @@ const ArrowButton = styled.button`
background-color: rgba(0, 0, 0, 0.7);
}
- ${({ direction }) => (direction === 'left' ? 'left: 10px;' : 'right: 10px;')}
+ ${({ direction }) => (direction === "left" ? "left: 10px;" : "right: 10px;")}
`;
const OrderContainer = styled.div`
@@ -312,33 +322,33 @@ const NoPetsMessage = styled.div`
`;
const PetAddButton = styled.button`
- background-color: #D0D0D0;
- margin-left: 100px;
- padding: 5px 10px;
- margin-right:8px;
- font-size: 11px;
- border-radius: 10px;
- color: #fff;
-
+ background-color: #d0d0d0;
+ margin-left: 100px;
+ padding: 5px 10px;
+ margin-right: 8px;
+ font-size: 11px;
+ border-radius: 10px;
+ color: #fff;
+
&:hover {
- background-color: #D0D0D0;
- transform: translateY(0);
+ background-color: #d0d0d0;
+ transform: translateY(0);
background-color: #b0b0b0;
}
`;
const PetDeleteBtn = styled.button`
- background-color: #D0D0D0;
+ background-color: #d0d0d0;
color: #fff;
border: none;
border-radius: 10px;
padding: 5px 10px;
font-size: 11px;
-
+
&:hover {
- background-color: #D0D0D0;
- transform: translateY(0);
+ background-color: #d0d0d0;
+ transform: translateY(0);
background-color: #b0b0b0;
}
@@ -354,9 +364,9 @@ function MyPage() {
useEffect(() => {
const fetchUserDataAndPets = async () => {
- const userId = localStorage.getItem('userId');
+ const userId = localStorage.getItem("userId");
if (!userId) {
- console.error('유저데이터 없음');
+ console.error("유저데이터 없음");
return;
}
@@ -364,10 +374,10 @@ function MyPage() {
const userResponse = await axios.get(`/user/${userId}`);
setUserData(userResponse.data);
- const petsResponse = await axios.get('/pets');
+ const petsResponse = await axios.get("/pets");
setAllPets(petsResponse.data);
} catch (error) {
- console.error('데이터를 가져오는 중 오류 발생:', error);
+ console.error("데이터를 가져오는 중 오류 발생:", error);
}
};
@@ -375,40 +385,39 @@ function MyPage() {
}, []);
useEffect(() => {
- const userId = parseInt(localStorage.getItem('userId'), 10);
+ const userId = parseInt(localStorage.getItem("userId"), 10);
if (allPets.length > 0 && userId) {
- const userPets = allPets.filter(pet => pet.user === userId);
+ const userPets = allPets.filter((pet) => pet.user === userId);
setFilteredPets(userPets);
}
}, [allPets]);
- const userId = localStorage.getItem('userId');
+ const userId = localStorage.getItem("userId");
const handleDeletePet = async (petId) => {
try {
await axios.delete(`/pets/${petId}`);
- setFilteredPets(filteredPets.filter(pet => pet.petId !== petId));
- alert('펫이 삭제되었습니다.');
+ setFilteredPets(filteredPets.filter((pet) => pet.petId !== petId));
} catch (error) {
- console.error('펫 삭제 중 오류 발생:', error);
- alert('펫 삭제에 실패했습니다.');
+ console.error("펫 삭제 중 오류 발생:", error);
}
};
-
+
const userActivities = [
- { src: images.myActivity, alt: '내 활동', text: '내 활동' },
- { src: images.bogwan, alt: '보관 게시글', text: '보관 게시글' },
- { src: images.imseeJeojang, alt: '결제내역', text: '결제내역' },
- { src: images.alert, alt: '알림 목록', text: '알림 목록' },
- { src: images.hide, alt: '숨긴 게시글', text: '숨긴 게시글' },
- { src: images.blockHand, alt: '차단 목록', text: '차단 목록' },
+ { src: images.myActivity, alt: "내 활동", text: "내 활동" },
+ { src: images.bogwan, alt: "보관 게시글", text: "보관 게시글" },
+ { src: images.imseeJeojang, alt: "결제내역", text: "결제내역" },
+ { src: images.alert, alt: "알림 목록", text: "알림 목록" },
+ { src: images.hide, alt: "숨긴 게시글", text: "숨긴 게시글" },
+ { src: images.blockHand, alt: "차단 목록", text: "차단 목록" },
];
- const scroll = direction => {
+ const scroll = (direction) => {
const { current } = cardContainerRef;
if (current) {
- const scrollAmount = direction === 'left' ? -current.clientWidth : current.clientWidth;
- current.scrollBy({ left: scrollAmount, behavior: 'smooth' });
+ const scrollAmount =
+ direction === "left" ? -current.clientWidth : current.clientWidth;
+ current.scrollBy({ left: scrollAmount, behavior: "smooth" });
}
};
@@ -418,32 +427,51 @@ function MyPage() {
- {userData ? userData.nickname : '불러오는 중...'}
- navigate(`/myPage/${userId}/editUserRegister/${userId}`)}>수정
+ {userData ? userData.nickname : "불러오는 중..."}
+
+ navigate(`/myPage/${userId}/editUserRegister/${userId}`)
+ }
+ >
+ 수정
+
- scroll('left')}>
+ scroll("left")}>
{filteredPets.length > 0 ? (
- filteredPets.map(pet => (
+ filteredPets.map((pet) => (
우리응애
- navigate(`/myPage/${userId}/petRegister`)}>추가
- handleDeletePet(pet.petId)}>삭제
+
+ navigate(`/myPage/${userId}/petRegister`)
+ }
+ >
+ 추가
+
+ handleDeletePet(pet.petId)}>
+ 삭제
+
-
{pet.petName}응애
@@ -453,10 +481,21 @@ function MyPage() {
{pet.petWeight}kg
navigate(`/myPage/${userId}/missingRegister/${pet.petId}`)}>
+ onClick={() =>
+ navigate(
+ `/myPage/${userId}/missingRegister/${pet.petId}`
+ )
+ }
+ >
실종등록
- navigate(`/myPage/${userId}/editPetRegister/${pet.petId}`)}>
+
+ navigate(
+ `/myPage/${userId}/editPetRegister/${pet.petId}`
+ )
+ }
+ >
수정
@@ -467,21 +506,33 @@ function MyPage() {
) : (
등록된 펫이 없습니다
- navigate(`/myPage/${userId}/petRegister`)}>펫 등록하기
+ navigate(`/myPage/${userId}/petRegister`)}
+ >
+ 펫 등록하기
+
)}
- scroll('right')}>
+ scroll("right")}>
- navigate('/orderList')} />
+ navigate("/orderList")}
+ />
주문내역
- navigate('/paymentHistory')}/>
+ navigate("/paymentHistory")}
+ />
결제내역
@@ -528,9 +579,9 @@ function MyPage() {
{
- alert('성공적으로 로그아웃 되었습니다');
- navigate('/');
- }}>
+ navigate("/");
+ }}
+ >
로그아웃
diff --git a/src/pages/MyPage/PetEditPage.jsx b/src/pages/MyPage/PetEditPage.jsx
index 6b5b350..f26670a 100644
--- a/src/pages/MyPage/PetEditPage.jsx
+++ b/src/pages/MyPage/PetEditPage.jsx
@@ -198,7 +198,6 @@ const PetEditPage = () => {
});
if (response.status === 200) {
- alert('반려동물 수정이 완료되었습니다.');
navigate('/myPage/:userId');
} else {
alert('등록 중 오류가 발생했습니다. 다시 시도해주세요.');
diff --git a/src/pages/MyPage/RegisterMissing.jsx b/src/pages/MyPage/RegisterMissing.jsx
index eb5aead..31abd29 100644
--- a/src/pages/MyPage/RegisterMissing.jsx
+++ b/src/pages/MyPage/RegisterMissing.jsx
@@ -1,8 +1,8 @@
-import React, { useState, useEffect } from 'react';
-import styled from 'styled-components';
-import { useNavigate } from 'react-router-dom';
-import { useParams } from 'react-router-dom';
-import axios from '../../apis/AxiosInstance';
+import React, { useState, useEffect } from "react";
+import styled from "styled-components";
+import { useNavigate } from "react-router-dom";
+import { useParams } from "react-router-dom";
+import axios from "../../apis/AxiosInstance";
const ScrollableContainer = styled.div`
max-height: 100%;
border: 1px solid #ddd;
@@ -41,7 +41,7 @@ const InputContainer = styled.div`
const StyledInput = styled.input`
width: 100%;
padding: 10px 20px 10px 10px;
- border: 1px solid #E4E4E4;
+ border: 1px solid #e4e4e4;
border-radius: 5px;
font-size: 11px;
margin-bottom: 10px;
@@ -62,8 +62,8 @@ const EditButton = styled.button`
right: 10px;
top: 40%;
transform: translateY(-50%);
- background-color: #FFEFEF;
- color: #FF6E00;
+ background-color: #ffefef;
+ color: #ff6e00;
border: none;
border-radius: 8px;
cursor: pointer;
@@ -74,13 +74,13 @@ const EditButton = styled.button`
padding: 5px 10px;
transition: background-color 0.3s;
&:hover {
- background-color: #FFD3D3;
+ background-color: #ffd3d3;
}
`;
const ImageContainer = styled.div`
width: 125px;
height: 125px;
- border: 1px solid #E4E4E4;
+ border: 1px solid #e4e4e4;
border-radius: 8px;
display: flex;
align-items: center;
@@ -88,7 +88,7 @@ const ImageContainer = styled.div`
overflow: hidden;
cursor: pointer;
position: relative;
- background-color: #F8F8F8;
+ background-color: #f8f8f8;
`;
const PlaceholderText = styled.span`
color: #888;
@@ -105,7 +105,7 @@ const PreviewImage = styled.img`
const StyledTextarea = styled.textarea`
width: 100%;
padding: 10px;
- border: 1px solid #E4E4E4;
+ border: 1px solid #e4e4e4;
border-radius: 5px;
font-size: 11px;
resize: none;
@@ -115,7 +115,7 @@ const RegisterButton = styled.button`
display: flex;
justify-content: center;
align-items: center;
- border: 1px solid #E4E4E4;
+ border: 1px solid #e4e4e4;
width: 100%;
height: 43px;
text-align: center;
@@ -123,19 +123,19 @@ const RegisterButton = styled.button`
margin-top: 10px;
margin-bottom: 70px;
&:hover {
- background-color: #FF6E00;
+ background-color: #ff6e00;
color: white;
}
`;
const RegisterMissing = () => {
const navigate = useNavigate();
const { userId, petId } = useParams();
- const [petName, setPetName] = useState('');
- const [date, setDate] = useState('');
- const [address, setAddress] = useState('');
- const [phone, setPhone] = useState('');
- const [description, setDescription] = useState('');
- const [locationInput, setLocationInput] = useState('');
+ const [petName, setPetName] = useState("");
+ const [date, setDate] = useState("");
+ const [address, setAddress] = useState("");
+ const [phone, setPhone] = useState("");
+ const [description, setDescription] = useState("");
+ const [locationInput, setLocationInput] = useState("");
const [map, setMap] = useState(null);
const [marker, setMarker] = useState(null);
const [latitude, setLatitude] = useState(37.5665);
@@ -154,7 +154,7 @@ const RegisterMissing = () => {
}
}
} catch (error) {
- console.error('Error fetching walk routes:', error);
+ console.error("Error fetching walk routes:", error);
}
};
fetchWalkRouteId();
@@ -174,52 +174,50 @@ const RegisterMissing = () => {
const handleSubmit = async () => {
const formData = new FormData();
-
const walkrouteId = 2;
- formData.append('petId', petId);
- formData.append('userId', userId);
- formData.append('walkroute', walkrouteId); // 가져온 walkrouteId 사용
- formData.append('location', locationInput);
- formData.append('alarmName', '고창준');
- formData.append('missingDate', `${date}T00:00:00+09:00`);
- formData.append('alertradiuskm', 1);
- formData.append('petName', petName);
- formData.append('missingstatus', 1);
- formData.append('formDetail', latitude);
- formData.append('date', date);
- formData.append('address', address);
- formData.append('contactNumber', phone);
- formData.append('missingDetails', description);
- formData.append('createdAt', new Date().toISOString());
+ formData.append("petId", petId);
+ formData.append("userId", userId);
+ formData.append("walkroute", walkrouteId); // 가져온 walkrouteId 사용
+ formData.append("location", locationInput);
+ formData.append("alarmName", "고창준");
+ formData.append("missingDate", `${date}T00:00:00+09:00`);
+ formData.append("alertradiuskm", 1);
+ formData.append("petName", petName);
+ formData.append("missingstatus", 1);
+ formData.append("formDetail", latitude);
+ formData.append("date", date);
+ formData.append("address", address);
+ formData.append("contactNumber", phone);
+ formData.append("missingDetails", description);
+ formData.append("createdAt", new Date().toISOString());
const imageInput = document.querySelector('input[type="file"]');
if (imageInput.files[0]) {
- formData.append('imageUrl', imageInput.files[0]);
+ formData.append("imageUrl", imageInput.files[0]);
}
try {
- const response = await axios.post('/missings', formData, {
+ const response = await axios.post("/missings", formData, {
headers: {
- 'Content-Type': 'multipart/form-data',
+ "Content-Type": "multipart/form-data",
},
});
if (response.status === 201) {
if (userId) {
- alert('실종등록이 완료되었습니다.');
navigate(`/myPage/${userId}/missingSave`);
} else {
- console.error('User ID not found in local storage');
- alert('사용자 ID를 받아오는데 실패했습니다.');
+ console.error("User ID not found in local storage");
+ alert("사용자 ID를 받아오는데 실패했습니다.");
}
} else {
- alert('등록 중 오류가 발생했습니다. 다시 시도해주세요.');
+ alert("등록 중 오류가 발생했습니다. 다시 시도해주세요.");
}
} catch (error) {
- console.error('Error registering pet:', error);
- alert('서버와 통신 중 오류가 발생했습니다.');
+ console.error("Error registering pet:", error);
+ alert("서버와 통신 중 오류가 발생했습니다.");
}
};
useEffect(() => {
- const container = document.getElementById('map');
+ const container = document.getElementById("map");
const options = {
center: new window.kakao.maps.LatLng(latitude, longitude),
level: 3,
@@ -235,57 +233,75 @@ const RegisterMissing = () => {
const searchAddrFromCoords = (coords, callback) => {
geocoder.coord2Address(coords.getLng(), coords.getLat(), callback);
};
- window.kakao.maps.event.addListener(newMap, 'click', (mouseEvent) => {
+ window.kakao.maps.event.addListener(newMap, "click", (mouseEvent) => {
const clickedPosition = mouseEvent.latLng;
newMarker.setPosition(clickedPosition);
setLatitude(clickedPosition.getLat());
setLongitude(clickedPosition.getLng());
- searchAddrFromCoords(clickedPosition, function(result, status) {
+ searchAddrFromCoords(clickedPosition, function (result, status) {
if (status === window.kakao.maps.services.Status.OK) {
- const addr = result[0].road_address ? result[0].road_address.address_name : result[0].address.address_name;
+ const addr = result[0].road_address
+ ? result[0].road_address.address_name
+ : result[0].address.address_name;
setLocationInput(`주소: ${addr}`);
}
});
});
// 초기 위치의 주소 가져오기
- searchAddrFromCoords(new window.kakao.maps.LatLng(latitude, longitude), function(result, status) {
- if (status === window.kakao.maps.services.Status.OK) {
- const addr = result[0].road_address ? result[0].road_address.address_name : result[0].address.address_name;
- setLocationInput(`${addr}`);
+ searchAddrFromCoords(
+ new window.kakao.maps.LatLng(latitude, longitude),
+ function (result, status) {
+ if (status === window.kakao.maps.services.Status.OK) {
+ const addr = result[0].road_address
+ ? result[0].road_address.address_name
+ : result[0].address.address_name;
+ setLocationInput(`${addr}`);
+ }
}
- });
+ );
}, [latitude, longitude]);
const getCurrentLocation = () => {
if (navigator.geolocation) {
- navigator.geolocation.getCurrentPosition((position) => {
- const { latitude, longitude } = position.coords;
- setLatitude(latitude);
- setLongitude(longitude);
- const geocoder = new window.kakao.maps.services.Geocoder();
- const coord = new window.kakao.maps.LatLng(latitude, longitude);
- geocoder.coord2Address(coord.getLng(), coord.getLat(), (result, status) => {
- if (status === window.kakao.maps.services.Status.OK) {
- const addr = result[0].road_address ? result[0].road_address.address_name : result[0].address.address_name;
- setLocationInput(`주소: ${addr}`);
- }
- });
- }, (error) => {
- console.error("위치 정보에 접근할 수 없습니다.", error);
- alert("위치 정보를 가져올 수 없습니다. 브라우저 설정을 확인해 주세요.");
- });
+ navigator.geolocation.getCurrentPosition(
+ (position) => {
+ const { latitude, longitude } = position.coords;
+ setLatitude(latitude);
+ setLongitude(longitude);
+ const geocoder = new window.kakao.maps.services.Geocoder();
+ const coord = new window.kakao.maps.LatLng(latitude, longitude);
+ geocoder.coord2Address(
+ coord.getLng(),
+ coord.getLat(),
+ (result, status) => {
+ if (status === window.kakao.maps.services.Status.OK) {
+ const addr = result[0].road_address
+ ? result[0].road_address.address_name
+ : result[0].address.address_name;
+ setLocationInput(`주소: ${addr}`);
+ }
+ }
+ );
+ },
+ (error) => {
+ console.error("위치 정보에 접근할 수 없습니다.", error);
+ alert(
+ "위치 정보를 가져올 수 없습니다. 브라우저 설정을 확인해 주세요."
+ );
+ }
+ );
} else {
alert("이 브라우저는 Geolocation을 지원하지 않습니다.");
}
};
const handleDateChange = (e) => {
- const value = e.target.value.replace(/[^0-9]/g, '');
- let formattedValue = '';
+ const value = e.target.value.replace(/[^0-9]/g, "");
+ let formattedValue = "";
if (value.length > 4) {
formattedValue += value.substring(0, 4);
- formattedValue += '-';
+ formattedValue += "-";
if (value.length > 6) {
formattedValue += value.substring(4, 6);
- formattedValue += '-';
+ formattedValue += "-";
formattedValue += value.substring(6, 8);
} else if (value.length > 4) {
formattedValue += value.substring(4, 6);
@@ -296,16 +312,16 @@ const RegisterMissing = () => {
setDate(formattedValue);
};
const handlePhoneChange = (e) => {
- const value = e.target.value.replace(/[^0-9]/g, '');
- let formattedValue = '';
+ const value = e.target.value.replace(/[^0-9]/g, "");
+ let formattedValue = "";
if (value.length > 0) {
formattedValue += value.substring(0, 3);
}
if (value.length > 3) {
- formattedValue += '-' + value.substring(3, 7);
+ formattedValue += "-" + value.substring(3, 7);
}
if (value.length > 7) {
- formattedValue += '-' + value.substring(7,11);
+ formattedValue += "-" + value.substring(7, 11);
}
setPhone(formattedValue);
};
@@ -321,20 +337,32 @@ const RegisterMissing = () => {
실종 날짜
-
+
핸드폰 번호
-
+
아이 사진
-
document.getElementById('imageUpload').click()}>
+ document.getElementById("imageUpload").click()}
+ >
{previewImage ? (
) : (
@@ -342,11 +370,15 @@ const RegisterMissing = () => {
)}
상세정보
- setDescription(e.target.value)} />
+ setDescription(e.target.value)}
+ />
등록하기
);
};
-export default RegisterMissing;
\ No newline at end of file
+export default RegisterMissing;
diff --git a/src/pages/RegisterPage/PetRegisterPage.jsx b/src/pages/RegisterPage/PetRegisterPage.jsx
index be06e38..2a5ba26 100644
--- a/src/pages/RegisterPage/PetRegisterPage.jsx
+++ b/src/pages/RegisterPage/PetRegisterPage.jsx
@@ -1,12 +1,11 @@
-import React, { useState, useEffect } from 'react';
-import styled from 'styled-components';
-import { useNavigate } from 'react-router-dom';
-import { CatList, DogList } from '../../components/Register/PetData';
-import SelectBox from '../../components/Register/SelectBox';
-import UploadImg from '../../components/Register/UploadImg';
-import axios from '../../apis/AxiosInstance';
-import { ScrollableContainer, Container, Label } from './CommonStyle';
-
+import React, { useState, useEffect } from "react";
+import styled from "styled-components";
+import { useNavigate } from "react-router-dom";
+import { CatList, DogList } from "../../components/Register/PetData";
+import SelectBox from "../../components/Register/SelectBox";
+import UploadImg from "../../components/Register/UploadImg";
+import axios from "../../apis/AxiosInstance";
+import { ScrollableContainer, Container, Label } from "./CommonStyle";
const StyledInput = styled.input`
padding: 13px;
@@ -23,7 +22,7 @@ const SelectButtonContainer = styled.div`
`; // 버튼 선택 컨테이너
const SelectButton = styled.button`
- color: ${({ selected }) => (selected ? 'white' : 'black')};
+ color: ${({ selected }) => (selected ? "white" : "black")};
display: flex;
justify-content: center;
align-items: center;
@@ -32,7 +31,7 @@ const SelectButton = styled.button`
height: 40px;
text-align: center;
border-radius: 5px;
- background-color: ${({ selected }) => (selected ? '#FF6E00' : 'white')};
+ background-color: ${({ selected }) => (selected ? "#FF6E00" : "white")};
cursor: pointer;
font-size: 11px;
font-weight: 500;
@@ -76,66 +75,65 @@ const LastComment = styled.span`
const getCurrentDate = () => {
const today = new Date();
const year = today.getFullYear();
- const month = String(today.getMonth() + 1).padStart(2, '0');
- const day = String(today.getDate()).padStart(2, '0');
+ const month = String(today.getMonth() + 1).padStart(2, "0");
+ const day = String(today.getDate()).padStart(2, "0");
return `${year}-${month}-${day}`;
};
const PetRegisterPage = () => {
const navigate = useNavigate();
- const [imgPath, setImgPath] = useState('');
- const [selectedPetType, setSelectedPetType] = useState('');
- const [petName, setPetName] = useState('');
- const [birthdate, setBirthdate] = useState('');
+ const [imgPath, setImgPath] = useState("");
+ const [selectedPetType, setSelectedPetType] = useState("");
+ const [petName, setPetName] = useState("");
+ const [birthdate, setBirthdate] = useState("");
const [selectedGender, setSelectedGender] = useState(null);
const [isNeutered, setIsNeutered] = useState(null);
const [isAllergic, setIsAllergic] = useState(null);
- const [weight, setWeight] = useState('');
+ const [weight, setWeight] = useState("");
const [userId, setUserId] = useState(null);
const [selectCatList, setSelectCatList] = useState(null);
const [selectDogList, setSelectDogList] = useState(null);
useEffect(() => {
- const storedUserId = localStorage.getItem('userId');
+ const storedUserId = localStorage.getItem("userId");
if (storedUserId) {
setUserId(storedUserId);
}
- setBirthdate('2020-01-01');
+ setBirthdate("2020-01-01");
}, []);
- const handlePetTypeClick = value => setSelectedPetType(value);
- const handleGenderClick = gender => setSelectedGender(gender);
- const handleNeuteredClick = value => setIsNeutered(value);
- const handleAllergicClick = value => setIsAllergic(value);
- const handlePetNameChange = e => setPetName(e.target.value);
- const handleBirthdateChange = e => setBirthdate(e.target.value);
- const handleCatChange = e => setSelectCatList(e.target.value);
- const handleDogChange = e => setSelectDogList(e.target.value);
- const handleWeightChange = e => {
+ const handlePetTypeClick = (value) => setSelectedPetType(value);
+ const handleGenderClick = (gender) => setSelectedGender(gender);
+ const handleNeuteredClick = (value) => setIsNeutered(value);
+ const handleAllergicClick = (value) => setIsAllergic(value);
+ const handlePetNameChange = (e) => setPetName(e.target.value);
+ const handleBirthdateChange = (e) => setBirthdate(e.target.value);
+ const handleCatChange = (e) => setSelectCatList(e.target.value);
+ const handleDogChange = (e) => setSelectDogList(e.target.value);
+ const handleWeightChange = (e) => {
const value = e.target.value;
if (/^\d*\.?\d*$/.test(value)) setWeight(value);
};
- const handleRegister = async event => {
-
+ const handleRegister = async (event) => {
event.preventDefault();
if (!validateForm()) return;
const formData = new FormData();
if (imgPath) {
- formData.append('image', imgPath);
+ formData.append("image", imgPath);
}
const petData = {
user: userId,
petName: petName,
dogOrCat: selectedPetType,
- petType: selectedPetType === '고양이' ? selectCatList : selectDogList,
+ petType: selectedPetType === "고양이" ? selectCatList : selectDogList,
petWeight: parseInt(weight),
- neutering: isNeutered === '네',
- petAllergy: isAllergic === '네',
- gender: selectedGender === '남아',
+ neutering: isNeutered === "네",
+ petAllergy: isAllergic === "네",
+ gender: selectedGender === "남아",
createdAt: new Date().toISOString(),
petAge: calculateAge(birthdate),
};
@@ -147,28 +145,30 @@ const PetRegisterPage = () => {
}
try {
- const response = await axios.post('/pets', formData, {
+ const response = await axios.post("/pets", formData, {
headers: {
- 'Content-Type': 'multipart/form-data',
+ "Content-Type": "multipart/form-data",
},
});
if (response.status === 201) {
- navigate('/');
- alert('발바닥천국에 오신 것을 환영합니다!')
+ navigate("/");
} else {
- alert('등록 중 오류가 발생했습니다. 다시 시도해주세요.');
+ alert("등록 중 오류가 발생했습니다. 다시 시도해주세요.");
}
} catch (error) {
- alert('서버와 통신 중 오류가 발생했습니다.');
+ alert("서버와 통신 중 오류가 발생했습니다.");
}
};
- const calculateAge = birthdate => {
+ const calculateAge = (birthdate) => {
const today = new Date();
const birthDate = new Date(birthdate);
const age = today.getFullYear() - birthDate.getFullYear();
const monthDiff = today.getMonth() - birthDate.getMonth();
- if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
+ if (
+ monthDiff < 0 ||
+ (monthDiff === 0 && today.getDate() < birthDate.getDate())
+ ) {
return age - 1;
}
return age;
@@ -176,39 +176,39 @@ const PetRegisterPage = () => {
const validateForm = () => {
if (!selectedPetType) {
- alert('반려동물 종류를 선택해주세요.');
+ alert("반려동물 종류를 선택해주세요.");
return false;
}
if (!petName) {
- alert('응애 이름을 입력해주세요.');
+ alert("응애 이름을 입력해주세요.");
return false;
}
if (!birthdate) {
- alert('생일을 입력해주세요.');
+ alert("생일을 입력해주세요.");
return false;
}
if (!selectedGender) {
- alert('성별을 선택해주세요.');
+ alert("성별을 선택해주세요.");
return false;
}
- if (selectedPetType === '고양이' && !selectCatList) {
- alert('묘종을 선택해주세요.');
+ if (selectedPetType === "고양이" && !selectCatList) {
+ alert("묘종을 선택해주세요.");
return false;
}
- if (selectedPetType === '강아지' && !selectDogList) {
- alert('견종을 선택해주세요.');
+ if (selectedPetType === "강아지" && !selectDogList) {
+ alert("견종을 선택해주세요.");
return false;
}
if (!isNeutered) {
- alert('중성화 여부를 선택해주세요.');
+ alert("중성화 여부를 선택해주세요.");
return false;
}
if (!weight) {
- alert('몸무게를 입력해주세요.');
+ alert("몸무게를 입력해주세요.");
return false;
}
if (!isAllergic) {
- alert('알러지 여부를 선택해주세요.');
+ alert("알러지 여부를 선택해주세요.");
return false;
}
return true;
@@ -220,10 +220,16 @@ const PetRegisterPage = () => {
- handlePetTypeClick('강아지')}>
+ handlePetTypeClick("강아지")}
+ >
강아지
- handlePetTypeClick('고양이')}>
+ handlePetTypeClick("고양이")}
+ >
고양이
@@ -236,7 +242,7 @@ const PetRegisterPage = () => {
required
/>
- {selectedPetType === '고양이' && (
+ {selectedPetType === "고양이" && (
<>
{
>
)}
- {selectedPetType === '강아지' && (
+ {selectedPetType === "강아지" && (
<>
{
/>
>
)}
-
- 생일
+ {
/>
- handleGenderClick('남아')}>
+ handleGenderClick("남아")}
+ >
남아
- handleGenderClick('여아')}>
+ handleGenderClick("여아")}
+ >
여아
- handleNeuteredClick('네')}>
+ handleNeuteredClick("네")}
+ >
네
- handleNeuteredClick('아니요')}>
+ handleNeuteredClick("아니요")}
+ >
아니요
@@ -306,19 +324,25 @@ const PetRegisterPage = () => {
- handleAllergicClick('네')}>
+ handleAllergicClick("네")}
+ >
네
- handleAllergicClick('아니요')}>
+ handleAllergicClick("아니요")}
+ >
아니요
등록하기
- navigate('/')}>예비 집사입니다
+ navigate("/")}>예비 집사입니다
);
};
-export default PetRegisterPage;
\ No newline at end of file
+export default PetRegisterPage;