Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FE] 사진 추가한 후 다시 접속 시 반영이 되지 않는 버그 #727

Merged
merged 5 commits into from
Oct 10, 2024
Merged
31 changes: 23 additions & 8 deletions client/src/apis/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type RequestInitWithMethod = Omit<RequestInit, 'method'> & {method: Method};

type HeadersType = [string, string][] | Record<string, string> | Headers;

export type Body = BodyInit | object | null;
export type Body = BodyInit | object | null; //init안에 FormDATA있음.

type RequestProps = {
baseUrl?: string;
Expand All @@ -32,6 +32,12 @@ type RequestProps = {
method: Method;
};

type CreateRequestInitProps = {
body?: Body;
method: Method;
headers?: HeadersType;
};

type RequestMethodProps = Omit<RequestProps, 'method'>;

type FetchType = {
Expand Down Expand Up @@ -85,17 +91,26 @@ const prepareRequest = ({baseUrl = API_BASE_URL, method, endpoint, headers, body

if (queryParams) url += `?${objectToQueryString(queryParams)}`;

const requestInit = createRequestInit({method, headers, body});

return {url, requestInit};
};

const createRequestInit = ({method, headers, body}: CreateRequestInitProps) => {
const requestInit: RequestInitWithMethod = {
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...headers,
},
method,
body: body ? JSON.stringify(body) : null,
};

return {url, requestInit};
if (body instanceof FormData) {
return {...requestInit, body};
} else {
return {
...requestInit,
headers: {...headers, 'Content-Type': 'application/json'},
body: body ? JSON.stringify(body) : null,
};
}
};

const executeRequest = async ({url, requestInit, errorHandlingStrategy}: WithErrorHandlingStrategy<FetchType>) => {
Expand All @@ -114,7 +129,7 @@ const executeRequest = async ({url, requestInit, errorHandlingStrategy}: WithErr
return response;
} catch (error) {
if (error instanceof Error) {
throw error; // 그대로 RequestError 또는 Error 인스턴스를 던집니다.
throw error;
}

throw error;
Expand Down
21 changes: 1 addition & 20 deletions client/src/apis/request/images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,7 @@ export interface RequestPostImages {
}

export const requestPostImages = async ({eventId, formData}: WithEventId<RequestPostImages>) => {
// return await requestPostWithoutResponse({
// baseUrl: BASE_URL.HD,
// endpoint: `${ADMIN_API_PREFIX}/${eventId}/images`,
// headers: {
// 'Content-Type': 'multipart/form-data',
// },
// body: formData,
// });

// TODO: (@todari): 기존의 request 방식들은 기본적으로
// header를 Content-Type : application/json 으로 보내주고 있음
// multipart/form-data 요청을 보내기 위해선 header Content-Type을 빈 객체로 전달해야 함
fetch(`${BASE_URL.HD}${ADMIN_API_PREFIX}/${eventId}/images`, {
credentials: 'include',
// headers: {
// 'Content-Type': 'multipart/form-data',
// },
method: 'POST',
body: formData,
});
await requestPostWithoutResponse({endpoint: `${ADMIN_API_PREFIX}/${eventId}/images`, body: formData});
};

export const requestGetImages = async ({eventId}: WithEventId) => {
Expand Down
6 changes: 3 additions & 3 deletions client/src/hooks/queries/images/useRequestPostImages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ const useRequestPostImages = () => {
const eventId = getEventIdByUrl();
const queryClient = useQueryClient();

const {mutate, ...rest} = useMutation({
const {mutateAsync, ...rest} = useMutation({
mutationFn: ({formData}: RequestPostImages) => requestPostImages({eventId, formData}),
onSuccess: () => {
queryClient.invalidateQueries({queryKey: [QUERY_KEYS.images]});
queryClient.removeQueries({queryKey: [QUERY_KEYS.images]});
},
});

return {postImages: mutate, ...rest};
return {postImages: mutateAsync, ...rest};
};

export default useRequestPostImages;
16 changes: 6 additions & 10 deletions client/src/hooks/useAddImagesPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const useAddImagesPage = () => {
const navigate = useNavigate();
const eventId = getEventIdByUrl();

const {postImages, isPending, isSuccess: isSuccessPostImage} = useRequestPostImages();
const {postImages, isPending} = useRequestPostImages();
const {deleteImage} = useRequestDeleteImage();

useEffect(() => {
Expand Down Expand Up @@ -57,15 +57,15 @@ const useAddImagesPage = () => {
deleteImage({
imageId: images[index].id,
});
setIsPrevImageDeleted(false);
setIsPrevImageDeleted(true);
} else {
setImages(prev => prev.filter((_, idx) => idx !== index));
}
};

const canSubmit = !!addedImages || isPrevImageDeleted;
const canSubmit = addedImages.length !== 0 || isPrevImageDeleted;

const submitImages = () => {
const submitImages = async () => {
const formData = new FormData();

if (!addedImages) return;
Expand All @@ -74,7 +74,8 @@ const useAddImagesPage = () => {
formData.append('images', addedImages[i], addedImages[i].name);
}

postImages({formData});
await postImages({formData});
navigate(`/event/${eventId}/admin`);
};

useEffect(() => {
Expand All @@ -85,11 +86,6 @@ const useAddImagesPage = () => {
};
}, []);

useEffect(() => {
if (!isSuccessPostImage) return;
navigate(`/event/${eventId}/admin`);
}, [isSuccessPostImage]);

return {fileInputRef, handleChangeImages, urls, handleDeleteImage, isPending, canSubmit, submitImages};
};

Expand Down
Loading