FormData를 사용한 경우FormData를 통해 데이터를 자동으로 객체화할 수 있어서,
axios.post에 data 객체를 그대로 전달할 수 있습니다.
이때 data에 모든 필드가 포함되므로 따로 title, body, userId를 하나씩 지정하지 않아도 돼요.
function handleCreateClick(e) {
e.preventDefault(); // 새로고침 방지
const formData = new FormData(e.target);
const data = Object.fromEntries(formData.entries()); // 모든 입력값을 객체로 변환
const now = new Date().toISOString();
data.createdAt = now; // 현재 시간 추가
axios.post('<http://localhost:8080/api/petItems>', data)
.then(response => console.log('등록된 데이터:', response.data))
.catch(error => console.error('오류 발생:', error));
e.target.reset(); // 폼 초기화
}
이렇게 하면 formData가 객체 형태로 변환된 data에 모든 필드값이 들어가므로,
axios.post에서 data만 넘기면 됩니다.
FormData 없이 axios를 사용하는 경우, 각 필드를 직접 객체에 지정해줘야 해요.
이 경우 title, body, userId 등을 state나 ref를 통해 관리하거나
폼 데이터에서 직접 값을 가져와서 사용해야 합니다.
import { useState } from 'react';
function MyForm() {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [userId, setUserId] = useState(1); // 임의로 userId 지정
const postData = () => {
axios.post('<http://localhost:8080/api/petItems>', {
title: title,
body: body,
userId: userId,
createdAt: new Date().toISOString(),
})
.then(response => console.log('등록된 데이터:', response.data))
.catch(error => console.error('오류 발생:', error));
};
return (
<form onSubmit={(e) => { e.preventDefault(); postData(); }}>
<input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="제목" required />
<textarea value={body} onChange={(e) => setBody(e.target.value)} placeholder="내용" required></textarea>
<button type="submit">등록</button>
</form>
);
}
이 방식은 각 입력 필드를 하나하나 상태로 관리하기 때문에
title, body, userId와 같은 필드를 하나씩 직접 지정해줘야 합니다.