From e9babe9a5d300b4a46c168eb4f483a0bf1ca5325 Mon Sep 17 00:00:00 2001 From: subinsong01 Date: Sun, 3 Nov 2024 04:00:18 +0900 Subject: [PATCH] =?UTF-8?q?feat(#7):=20=ED=8E=AB=20=EC=A0=95=EB=B3=B4=20?= =?UTF-8?q?=EB=93=B1=EB=A1=9D=20DB=20=EC=97=B0=EA=B2=B0=20=EC=84=B1?= =?UTF-8?q?=EA=B3=B5=20&=20=EC=8B=A4=EC=A2=85=EB=93=B1=EB=A1=9D=20?= =?UTF-8?q?=ED=8E=98=EC=9D=B4=EC=A7=80=20=EC=9D=B4=EB=AF=B8=EC=A7=80=20?= =?UTF-8?q?=EC=82=AC=EC=A7=84=20=EB=AF=B8=EB=A6=AC=EB=B3=B4=EA=B8=B0=20?= =?UTF-8?q?=EA=B0=80=EB=8A=A5=ED=95=98=EA=B2=8C=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.html | 2 +- src/components/Register/SelectBox.jsx | 4 +- src/components/common/SideNav.jsx | 2 + src/pages/MyPage/RegisterMissing.jsx | 78 +++++++-- src/pages/RegisterPage/PetRegisterPage.jsx | 187 +++++++++------------ 5 files changed, 144 insertions(+), 129 deletions(-) diff --git a/index.html b/index.html index b1009ca..ecc536f 100644 --- a/index.html +++ b/index.html @@ -1,5 +1,5 @@ - + diff --git a/src/components/Register/SelectBox.jsx b/src/components/Register/SelectBox.jsx index 6a1bf2c..e3214f4 100644 --- a/src/components/Register/SelectBox.jsx +++ b/src/components/Register/SelectBox.jsx @@ -39,8 +39,8 @@ const SelectBox = ({ options, value, onChange, placeholder, required }) => { - {options.map((option) => ( - ))} diff --git a/src/components/common/SideNav.jsx b/src/components/common/SideNav.jsx index 9177c5b..5008dad 100644 --- a/src/components/common/SideNav.jsx +++ b/src/components/common/SideNav.jsx @@ -42,6 +42,8 @@ const SideNav = () => { { path: '/myPage/editPetRegister', title: '응애 정보 수정' }, { path: '/myPage/missingRegister', title: '실종 등록' }, { path: '/myPage/missingSave', title: '실종 등록 완료' }, + {path : '/petRegister', title: '우리응애 등록'}, + {path : '/userRegister/:userId', title: '회원정보 등록'}, { path: '/myPage', title: '마이 페이지' }, { path: '/orderList/orderDetail/orderCancel', title: '주문 취소' }, { path: '/orderList/orderDetail', title: '주문 상세' }, diff --git a/src/pages/MyPage/RegisterMissing.jsx b/src/pages/MyPage/RegisterMissing.jsx index 276fb42..c78f491 100644 --- a/src/pages/MyPage/RegisterMissing.jsx +++ b/src/pages/MyPage/RegisterMissing.jsx @@ -14,6 +14,7 @@ const Container = styled.div` display: flex; flex-direction: column; `; + const SubContainer = styled.div` display: flex; flex-direction: column; @@ -95,11 +96,32 @@ const EditButton = styled.button` } `; -const ImageContainer = styled.input` +const ImageContainer = styled.div` width: 125px; height: 125px; border: 1px solid #E4E4E4; border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + cursor: pointer; + position: relative; + background-color: #f8f8f8; +`; + +const PlaceholderText = styled.span` + color: #888; + font-size: 12px; + text-align: center; +`; + +const PreviewImage = styled.img` + position: absolute; + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 8px; `; const StyledTextarea = styled.textarea` @@ -133,20 +155,33 @@ const RegisterButton = styled.button` const RegisterMissing = () => { const navigate = useNavigate(); - const [petName, setPetName] = useState(''); // 이름 - const [date, setDate] = useState(''); // 잃어버린 날짜 - const [address, setAddress] = 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 [description, setDescription] = useState(''); + const [locationInput, setLocationInput] = useState(''); const [map, setMap] = useState(null); const [marker, setMarker] = useState(null); const [latitude, setLatitude] = useState(37.5665); const [longitude, setLongitude] = useState(126.978); + const [previewImage, setPreviewImage] = useState(null); // 미리보기 이미지 상태 추가 + + const today = new Date().toISOString().split("T")[0]; + + const handleImageChange = (e) => { + const file = e.target.files[0]; + if (file) { + const reader = new FileReader(); + reader.onloadend = () => { + setPreviewImage(reader.result); // 미리보기 이미지 설정 + }; + reader.readAsDataURL(file); // 파일을 Data URL로 읽음 + } else { + setPreviewImage(null); // 이미지가 없으면 미리보기 초기화 + } + }; - const today = new Date().toISOString().split("T")[0]; // 오늘 날짜 형식 설정 - - // Axios 요청을 handle하는 부분 const handleSubmit = async () => { const formData = new FormData(); formData.append('petName', petName); @@ -155,7 +190,7 @@ const RegisterMissing = () => { formData.append('phone', phone); formData.append('description', description); formData.append('createdAt', new Date().toISOString()); - // 사진 파일 추가 + const imageInput = document.querySelector('input[type="file"]'); if (imageInput.files[0]) { formData.append('image', imageInput.files[0]); @@ -202,15 +237,12 @@ const RegisterMissing = () => { newMarker.setMap(newMap); setMarker(newMarker); - // 클릭 이벤트 리스너 추가 window.kakao.maps.event.addListener(newMap, 'click', (mouseEvent) => { const clickedPosition = mouseEvent.latLng; - - // 마커 위치 변경 newMarker.setPosition(clickedPosition); setLatitude(clickedPosition.getLat()); setLongitude(clickedPosition.getLng()); - setLocationInput(`위도: ${clickedPosition.getLat().toFixed(6)}, 경도: ${clickedPosition.getLng().toFixed(6)}`); // 위도 경도 업데이트 + setLocationInput(`위도: ${clickedPosition.getLat().toFixed(6)}, 경도: ${clickedPosition.getLng().toFixed(6)}`); }); }, [latitude, longitude]); @@ -220,7 +252,7 @@ const RegisterMissing = () => { const { latitude, longitude } = position.coords; setLatitude(latitude); setLongitude(longitude); - setLocationInput(`위도: ${latitude}, 경도: ${longitude}`); // 위도 경도 저장 + setLocationInput(`위도: ${latitude}, 경도: ${longitude}`); }, (error) => { console.error("위치 정보에 접근할 수 없습니다.", error); }); @@ -282,11 +314,23 @@ const RegisterMissing = () => { - 핸드폰 번호 + 핸드폰 번호 아이 사진 - + + document.getElementById('imageUpload').click()}> + {previewImage ? ( + + ) : ( + 사진 등록 + )} + 상세정보 setDescription(e.target.value)} /> 등록하기 diff --git a/src/pages/RegisterPage/PetRegisterPage.jsx b/src/pages/RegisterPage/PetRegisterPage.jsx index 30e8933..78094ab 100644 --- a/src/pages/RegisterPage/PetRegisterPage.jsx +++ b/src/pages/RegisterPage/PetRegisterPage.jsx @@ -1,6 +1,6 @@ -import React, { useState, useEffect } from 'react'; +import React, { useState } from 'react'; import styled from "styled-components"; -import { useNavigate, useLocation } from 'react-router-dom'; +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'; @@ -35,6 +35,16 @@ const StyledInput = styled.input` font-size: 11px; `; // 폼 input +const Icon = styled.img` + position: absolute; + top: 40%; + left: 300px; + transform: translateY(-8px); + width: 20px; + height: 20px; +`; //카카오 아이콘 + + const SelectButtonContainer = styled.div` display: flex; gap: 8px; @@ -87,72 +97,40 @@ const LastComment = styled.span` margin-bottom: 20px; cursor: pointer; - &:hover { - color: #FF6E00; - font-weight: bold; + &:hover { + color: #FF6E00; + font-weight: bold; } -`; +` + +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'); + return `${year}-${month}-${day}`; +}; -//js const PetRegisterPage = () => { const navigate = useNavigate(); - const location = useLocation(); - const [accessToken, setAccessToken] = useState(''); - const [refreshToken, setRefreshToken] = useState(''); - const [userId, setUserId] = useState(''); // 유저 ID - const [imgPath, setImgPath] = useState(''); // 이미지 - const [selectedPetType, setSelectedPetType] = useState(''); // 강아지 or 고양이 - const [petName, setPetName] = useState(''); // 이름 + const [imgPath, setImgPath] = useState(''); //이미지 + const [selectedPetType, setSelectedPetType] = useState(''); //강아지 or 고양이 + 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 [selectCatList, setSelectCatList] = useState(null); // cat list - const [age, setAge] = useState(''); - const [selectDogList, setSelectDogList] = useState(null); // dog list - const [jwtToken, setJwtToken] = useState(''); - - useEffect(() => { - const storedUserId = localStorage.getItem('userId'); - setUserId(storedUserId); // 가져온 유저 ID를 상태에 저장 - console.log('Loaded userId from localStorage:', storedUserId); - }, []); - + const [weight, setWeight] = useState(''); //몸무게 + const [userId, setUserId] = useState('1'); // 유저 ID + const [selectCatList, setSelectCatList] = useState(null); //cat list + const [selectDogList, setSelectDogList] = useState(null); //dog list -useEffect(() => { - const queryParams = new URLSearchParams(location.search); - const tokenFromUrl = queryParams.get('jwtToken'); - const accessFromUrl = queryParams.get('accessToken'); - const refreshFromUrl = queryParams.get('refreshToken'); - const userId = queryParams.get('userId'); - - if (tokenFromUrl && accessFromUrl && refreshFromUrl) { - localStorage.setItem('jwtToken', tokenFromUrl); - localStorage.setItem('accessToken', accessFromUrl); - localStorage.setItem('refreshToken', refreshFromUrl); - localStorage.setItem('userId',userId); - setJwtToken(tokenFromUrl); - setAccessToken(accessFromUrl); - setRefreshToken(refreshFromUrl); - setUserId(userId); - console.log('Tokens saved to localStorage:', { tokenFromUrl, accessFromUrl, refreshFromUrl,userId }); - } else { - console.log('Tokens not found in URL'); - } - }, [location]); - 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) => { - const selectedDate = e.target.value; - setBirthdate(selectedDate); - setAge(calculateAge(selectedDate)); - }; - + const handleBirthdateChange = (e) => setBirthdate(e.target.value); const handleUserIdChange = (e) => setUserId(e.target.value); const handleCatChange = (e) => setSelectCatList(e.target.value); const handleDogChange = (e) => setSelectDogList(e.target.value); @@ -160,7 +138,6 @@ useEffect(() => { const value = e.target.value; if (/^\d*\.?\d*$/.test(value)) setWeight(value); }; - const handleRegister = async (event) => { event.preventDefault(); @@ -172,8 +149,6 @@ useEffect(() => { formData.append('image', imgPath); } - - // 반려동물 정보 설정 const petData = { petName: petName, dogOrCat: selectedPetType, @@ -183,10 +158,9 @@ useEffect(() => { petAllergy: isAllergic === '네', gender: selectedGender === '남아', createdAt: new Date().toISOString(), - user: parseInt(userId), + user: parseInt(userId), // 일단 userId 고정값 사용함 > 변경 해야함 petAge: calculateAge(birthdate), }; - for (const key in petData) { if (petData.hasOwnProperty(key)) { @@ -198,21 +172,12 @@ useEffect(() => { const response = await axios.post('http://localhost:8080/api/pets', formData, { headers: { 'Content-Type': 'multipart/form-data', - Authorization: `Bearer ${jwtToken}`, // 토큰 사용 }, }); - - console.log('Server response:', response.data); - if (response.status === 201) { - const petId = response.data; - if (petId) { - alert('반려동물 등록이 완료되었습니다.'); - navigate(`/userRegister/${petId}`); - } else { - console.error('PetId not found in response'); - alert('반려동물 ID를 받아오는데 실패했습니다.'); - } + alert('반려동물 등록이 완료되었습니다.'); + navigate('/'); + console.log('Pet data:', petData); } else { alert('등록 중 오류가 발생했습니다. 다시 시도해주세요.'); } @@ -220,9 +185,8 @@ useEffect(() => { console.error('Error registering pet:', error); alert('서버와 통신 중 오류가 발생했습니다.'); } - } + }; - const calculateAge = (birthdate) => { const today = new Date(); const birthDate = new Date(birthdate); @@ -233,7 +197,6 @@ useEffect(() => { } return age; }; - const validateForm = () => { if (!selectedPetType) { alert('반려동물 종류를 선택해주세요.'); @@ -271,14 +234,13 @@ useEffect(() => { alert('알러지 여부를 선택해주세요.'); return false; } - return true; }; return ( - + { value={petName} onChange={handlePetNameChange} required - /> + /> - - - {selectedPetType === '고양이' && ( - <> - - - - )} + - {selectedPetType === '강아지' && ( - <> - - - - )} +{selectedPetType === '고양이' && ( + <> + + ({ + key: `cat-${index}`, // 고유한 키 설정 + value: cat.value, + label: cat.label, + }))} + value={selectCatList} + onChange={handleCatChange} + placeholder="묘종을 선택해주세요" + required + /> + +)} +{selectedPetType === '강아지' && ( + <> + + ({ + key: `dog-${index}`, // 고유한 키 설정 + value: dog.value, + label: dog.label, + }))} + value={selectDogList} + onChange={handleDogChange} + placeholder="견종을 선택해주세요" + required + /> + +)} - -