Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/apis/artwork-detail/postMySpace.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { instance } from '@/apis/axios';
import { TGetResponse } from '@/apis/type';
import { TMySpaceFormData } from './type';

/**
* 내 공간 등록 API 함수
* @param data 공간 등록 폼 데이터 (파일 전송을 위해 FormData 형태로 변환됩니다.)
* @returns 등록 결과를 포함한 응답(TGetResponse<void>)
* @author 김서윤
*/

export const postMySpace = async (
data: TMySpaceFormData
): Promise<TGetResponse<void>> => {
// 이미지 파일과 텍스트 필드를 함께 전송하기 위해 FormData 사용
const formData = new FormData();

if (data.images) {
formData.append('images', data.images);
}

// 나머지 텍스트 데이터 추가
formData.append('name', data.name);
formData.append('area', data.area);

const response = await instance.post<TGetResponse<void>>(
'/api/userspace',
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
);
console.log(response.data);
return response.data;
};
6 changes: 6 additions & 0 deletions src/apis/artwork-detail/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,9 @@ export type TOtherArtwork = {
title: string;
thumbnail: string;
};

export type TMySpaceFormData = {
images?: File;
name: string;
area: string;
};
12 changes: 12 additions & 0 deletions src/constants/mutationKey.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { postArtworkRegister } from '@/apis/artworkRegister/postArtworkRegister'
import { getAvailableArtworksQuery } from '@/constants/queryKeys';
import { postAuctionBid } from '@/apis/auction/postAuctionBid';
import { toggleArtworkLike } from '@/apis/artwork-like/like';
import { postMySpace } from '@/apis/artwork-detail/postMySpace';
/**
* 인증 회원가입 뮤테이션
* @author 홍규진
Expand Down Expand Up @@ -60,6 +61,17 @@ export const toggleArtworkLikeMutation = (artworkId: number) => {
};
};

/**
* 내 공간 등록 뮤테이션
* @author 김서윤
* */
export const postMySpaceMutation = () => {
return {
mutationKey: ['new_userspace'],
mutationFn: postMySpace,
};
};

/**
* 경매 좋아요 뮤테이션
* @author 이하늘
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ export const BottomContainer = styled.div`
padding: 16px 32px 24px;
`;

export const CloseBtn = styled.div<ButtonProps>`
export const CloseBtn = styled.button<ButtonProps>`
padding: 9px 38.5px;
background-color: ${({ $isCancle }) =>
$isCancle ? `${theme.colors.white}` : `${theme.colors.black}`};
Expand All @@ -118,6 +118,7 @@ export const CloseBtn = styled.div<ButtonProps>`
? `1px solid ${theme.colors.lightGray}`
: `1px solid ${theme.colors.black}`};
cursor: pointer;
outline: none;
display: flex;
justify-content: center;
align-items: center;
Expand Down
113 changes: 68 additions & 45 deletions src/pages/artwork-detail/components/MySpaceModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import {
FilePreview,
} from './index.style.ts';
import { Text } from '@/styles/text';
import useMySpaceForm from '@/pages/artwork-detail/hooks/useMySpaceForm.ts';
import { TMySpaceFormData } from '@/apis/artwork-detail/type';
import Close from '@/assets/svg/icon-close.svg';
import Upload from '@/assets/svg/space-register.svg';

Expand All @@ -30,6 +32,7 @@ interface MySpaceProps {

export const MySpaceModal = ({ onClose }: MySpaceProps) => {
const [imagePreview, setImagePreview] = useState<string | null>(null);
const { formData, setFormData, handleSubmit } = useMySpaceForm();

const handleProfileImageChange = (
event: React.ChangeEvent<HTMLInputElement>
Expand All @@ -41,6 +44,7 @@ export const MySpaceModal = ({ onClose }: MySpaceProps) => {
// 🔹 미리보기 이미지 URL 생성
const previewUrl = URL.createObjectURL(imageFile);
setImagePreview(previewUrl);
setFormData((prev: TMySpaceFormData) => ({ ...prev, images: imageFile }));
};

return (
Expand All @@ -56,53 +60,72 @@ export const MySpaceModal = ({ onClose }: MySpaceProps) => {
</Text>
<CloseIcon src={Close} onClick={onClose} alt="닫기" />
</TopContainer>
<CenterContainer>
<InformContainer>
<InputContainer>
<InputTitle>공간명</InputTitle>
<InputBox
placeholder="공간명을 입력해주세요"
$isName={true}
<form onSubmit={handleSubmit}>
<CenterContainer>
<InformContainer>
<InputContainer>
<InputTitle>공간명</InputTitle>
<InputBox
placeholder="공간명을 입력해주세요"
$isName={true}
value={formData.name}
onChange={(e) =>
setFormData((prev: TMySpaceFormData) => ({
...prev,
name: e.target.value,
}))
}
/>
</InputContainer>
<InputContainer>
<InputTitle>공간넓이</InputTitle>
<InputBox
$isName={false}
value={formData.area}
onChange={(e) =>
setFormData((prev: TMySpaceFormData) => ({
...prev,
area: e.target.value,
}))
}
/>
<Text size={14} color="font03gray" weight="medium">
m
</Text>
</InputContainer>
</InformContainer>

{/* 이미지 업로드 */}
<UploadContainer>
<UploadLabel htmlFor="file">
<UploadLabelImg src={Upload} alt="이미지 업로드" />
</UploadLabel>
<FileInput
type="file"
name="file"
id="file"
accept="image/*"
onChange={handleProfileImageChange}
/>
</InputContainer>
<InputContainer>
<InputTitle>공간넓이</InputTitle>
<InputBox $isName={false} />
<Text size={14} color="font03gray" weight="medium">
m
</Text>
</InputContainer>
</InformContainer>
{imagePreview && (
<FilePreview src={imagePreview} alt="Preview" />
)}
</UploadContainer>
</CenterContainer>

{/* 이미지 업로드 */}
<UploadContainer>
<UploadLabel htmlFor="file">
<UploadLabelImg src={Upload} alt="이미지 업로드" />
</UploadLabel>
<FileInput
type="file"
name="file"
id="file"
accept="image/*"
onChange={handleProfileImageChange}
/>
{imagePreview && (
<FilePreview src={imagePreview} alt="Preview" />
)}
</UploadContainer>
</CenterContainer>
<BottomContainer>
<CloseBtn onClick={onClose} $isCancle={true}>
<Text size={13} color="black" weight="regular">
취소
</Text>
</CloseBtn>
<CloseBtn onClick={onClose} $isCancle={false}>
<Text size={13} color="white" weight="regular">
확인
</Text>
</CloseBtn>
</BottomContainer>
<BottomContainer>
<CloseBtn type="button" onClick={onClose} $isCancle={true}>
<Text size={13} color="black" weight="regular">
취소
</Text>
</CloseBtn>
<CloseBtn type="submit" $isCancle={false}>
<Text size={13} color="white" weight="regular">
확인
</Text>
</CloseBtn>
</BottomContainer>
</form>
</ModalContent>
</ModalWrap>
</ModalSpace>
Expand Down
76 changes: 76 additions & 0 deletions src/pages/artwork-detail/hooks/useMySpaceForm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { postMySpaceMutation } from '@/constants/mutationKey';
import { TMySpaceFormData } from '@/apis/artwork-detail/type';
import { toast } from 'sonner';
import { useState } from 'react';
import { getAvailableArtworksQuery } from '@/constants/queryKeys';
const useMySpaceForm = () => {
const queryClient = useQueryClient();
const [formData, setFormData] = useState<TMySpaceFormData>({
images: undefined,
name: '',
area: '',
});

/**
* 유효성 검사 함수
* @param formData 폼 데이터
* @returns 유효성 검사 결과
* @author 김서윤
*/
const validateForm = (formData: TMySpaceFormData) => {
const { images, name, area } = formData;

if (!images || !name || !area) {
toast.error('모든 항목을 입력해주세요. 빈칸이 있습니다.');
return false;
}
return true;
};

/**
* 내 공간 등록 뮤테이션
* @author 김서윤
*/
const mutation = useMutation({
mutationKey: postMySpaceMutation().mutationKey,
mutationFn: (data: TMySpaceFormData) =>
postMySpaceMutation().mutationFn(data),
onSuccess: async () => {
toast.success('공간 등록이 성공적으로 완료되었습니다.');
queryClient.invalidateQueries({
queryKey: postMySpaceMutation().mutationKey,
});
await getAvailableArtworksQuery().queryFn();
},
onError: (error: Error) => {
toast.error(`공간 등록 실패: ${error.message}`);
},
});

/**
* 공간 등록 폼 제출 함수
* 비어있는 것도 알려주기
* @param e 폼 제출 이벤트
* @author 김서윤
*/
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (validateForm(formData)) {
await mutation.mutateAsync(formData);
} else {
//어차피 위에서 토스트 메시지 띄워줬으니 여기서는 리턴
return;
}
};

return {
formData,
setFormData,
handleSubmit,
isLoading: mutation.isPending,
isError: mutation.isError,
};
};

export default useMySpaceForm;
10 changes: 6 additions & 4 deletions src/pages/artwork-detail/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,9 @@ export const ArtworkDetail = () => {
};

const handleUserNextClick = () => {
if (startIndex + itemsPerPage >= userspaces.length) return;
if (startIndex + itemsPerPage >= combinedSpaces.length) return;
setStartIndex((prevIndex) =>
Math.min(prevIndex + itemsPerPage, userspaces.length - itemsPerPage)
Math.min(prevIndex + itemsPerPage, combinedSpaces.length - itemsPerPage)
);
};

Expand Down Expand Up @@ -272,9 +272,11 @@ export const ArtworkDetail = () => {
onClick={handleUserNextClick}
style={{
opacity:
startIndex + itemsPerPage >= userspaces.length ? 0.5 : 1,
startIndex + itemsPerPage >= combinedSpaces.length
? 0.5
: 1,
cursor:
startIndex + itemsPerPage >= userspaces.length
startIndex + itemsPerPage >= combinedSpaces.length
? 'default'
: 'pointer',
}}
Expand Down
Loading