Property 'title' does not exist on type 'EventTarget'.ts(2339)
2023. 9. 21. 00:08ㆍTrip to Next.js
"use client";
import { useRouter } from "next/navigation";
export default function Create() {
const router = useRouter();
return (
<form
action=""
onSubmit={(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const title = (e.target as HTMLFormElement).elements.title.value;
const body = (e.target as HTMLFormElement).elements.body.value;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ title, body }),
};
fetch(`http://localhost:9999/topics`, options)
.then((res) => res.json())
.then((result) => {
const lastid = result.id;
router.push(`/read/${lastid}`);
});
}}
>
<p>
<input type="text" name="title" placeholder="title" />
</p>
<p>
<textarea
name="body"
id=""
cols={30}
rows={10}
placeholder="body"
></textarea>
</p>
<p>
<input type="submit" value="create" />
</p>
</form>
);
}
next.js에서 Property 'title' does not exist on type 'EventTarget'.ts(2339) 이런 에러를 마주했다. title에 타입을 찾을 수 없다는데 보통 리액트에서 폼에서 이런 에러를 마주한 적이 없어서 난감했다. 뭔가 next.js만의 특별하게 form을 전달하는 방식이 있을 것이라 예상해서 답이 금방 나올 것 같았는데 그렇지는 않았다. 타입을 단언하는 방식으로 chatGPT가 알려주었는데 마음에 들지는 않았다.
"use client";
import { useRouter } from "next/navigation";
export default function Create() {
const router = useRouter();
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const title = formData.get("title") as string;
const body = formData.get("body") as string;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ title, body }),
};
try {
const response = await fetch(`http://localhost:9999/topics`, options);
if (!response.ok) {
throw new Error("Network response was not ok");
}
const result = await response.json();
const lastId = result.id;
router.push(`/read/${lastId}`);
} catch (error) {
console.error("Error:", error);
}
};
return (
<form action="" onSubmit={handleSubmit}>
<p>
<input type="text" name="title" placeholder="title" />
</p>
<p>
<textarea
name="body"
id=""
cols={30}
rows={10}
placeholder="body"
></textarea>
</p>
<p>
<input type="submit" value="create" />
</p>
</form>
);
}
폼데이터에 대해 더 알아볼 것...!
'Trip to Next.js' 카테고리의 다른 글
Next.js 맛보기 (0) | 2023.09.19 |
---|