#handle data using formData
1 messages · Page 1 of 1 (latest)
To handle form data in Next.js, you can use the FormData object. Here's an example of how you can handle form submission using FormData and Object.entries:
export default function Page() {
async function onSubmit(event) {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const rawFormData = Object.fromEntries(formData.entries())
const response = await fetch('/api/submit', {
method: 'POST',
body: JSON.stringify(rawFormData),
headers: {
'Content-Type': 'application/json',
},
})
// Handle response if necessary
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="title" />
<input type="text" name="body" />
<input type="date" name="checkIn" />
<input type="date" name="checkOut" />
<input type="text" name="guests" />
<input type="text" name="pricePerNight" />
<input type="file" name="feauturedImage" />
{/* Add inputs for galleryTour */}
<button type="submit">Submit</button>
</form>
)
}
In this example, Object.entries(formData.entries()) is used to convert the FormData object into a plain JavaScript object. This object is then stringified and sent as the body of a POST request to the '/api/submit' endpoint.
Please note that handling files (like feauturedImage and imageGallery) might require additional steps, as FormData entries for files are read as File objects, not as strings. You might need to handle them separately or use a library that can parse multipart/form-data on the server side.