챌린지 참여하기 기능을 만들던 중
TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
에러를 발견. 보통 api를 작성할 때 하나하나 다 적기가 귀찮아서 위에코드를 복붙해서 수정하는데 내가 POST로 요청해야 할 걸 실수로 GET으로 요청해서 생긴 에러였다..!
export const joinChallengeRequest = async (
token: string,
data: {
userId: number;
challengeId: number;
}
) => {
headers.set('Authorization', token);
const json = await (
await fetch(`${CHALLENGE_API_END_POINT}/join`, {
method: 'GET', // <- POST
body: JSON.stringify(data),
headers,
})
).json();
if (json.errorCode) throw json;
else return json;
};
이곳저곳 공통으로 쓰이는 타입들은 d.ts랑 내가 types.ts 파일을 만들
react-query를 이용해 비동기로 data를 받아오기 때문에 대부분 jsx 코드를 작성할 때 자바스크립트의 옵셔널체이닝 문법으로 data가 있으면 내부 프로퍼티를 참고해 표시한다 (data?.key
) 근데 보다시피 data를 아직 받아오지 못했거나 그러면 null 자료형일 수도 있기 때문에 저 사진처럼 빨간 줄이 마구 뜬다ㅜ
data?.title || '' 이런 식으로 작성할지 아니면 다른 문법이나 방법이 있는지 찾아보고, 함수같은 경우는 내부에서 파라미터가 어떤 형태인지 체크해야 하고
javascript null check operator 구글링..
// components/CalendarUI.tsx
import { useState } from 'react';
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css'; // css import
const CalendarUI = ({
open,
close,
mark,
className,
}: {
open: boolean;
close: () => void;
mark: string[];
className: string;
}) => {
const [value, onChange] = useState(new Date());
return open ? (
<div className={className}>
<button
className="bg-white border border-b-0 border-gray-400 px-1 font-bold"
onClick={close}
>
✕
</button>
<Calendar
value={value}
onChange={onChange}
formatDay={(locale, date) => String(new Date(date).getDate())}
className="select-none"
showNeighboringMonth={false}
tileContent={({ date, view }) => {
const localDateString = new Date(date).toLocaleDateString(); // 2022. 11. 1.
const splitLocalDate = localDateString.split('. ');
const formatDate = `${splitLocalDate[0]}-${
splitLocalDate[1]
}-${splitLocalDate[2].substring(0, splitLocalDate[2].length - 1)}`; // 2022-11-26
const startOrEnd =
(mark[0] === formatDate && '시작') || (mark[1] === formatDate && '종료');
if (startOrEnd) {
return (
<div className="flex justify-center items-center absoluteDiv">
<div
className={`text-xs md:text-sm font-semibold text-black bg-red-200 rounded-full`}
>
{startOrEnd}
</div>
</div>
);
}
return null;
}}
/>
</div>
) : null;
};
export default CalendarUI;