#Handle values with FormData
1 messages · Page 1 of 1 (latest)
Based on the information provided in the extracts, it seems like you're trying to handle form data in Next.js. The FormData object is used to store key-value pairs that you can send using methods like fetch() or axios().
However, it's important to note that FormData objects do not maintain the structure of nested objects or arrays. They flatten the structure into a set of string key-value pairs. This is why your galleryTour array is not being preserved in the structure you want.
If you need to maintain the structure of your data, you might need to consider stringifying your data into a JSON format before sending it. However, this would not work if you are including files in your form data.
Here's an example of how you can handle form data in Next.js:
export default function Page() {
async function createInvoice(formData: FormData) {
'use server'
const rawFormData = {
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
}
// mutate data
// revalidate cache
}
return <form action={createInvoice}>...</form>
}
(Source: Next.js Docs (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#forms))
For error handling in form submission, you can use React state:
import React, { useState, FormEvent } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null)
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setIsLoading(true)
setError(null) // Clear previous errors when a new request starts
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('Failed to submit the data. Please try again.')
}
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Capture the error message to display to the user
setError(error.message)
console.error(error)
} finally {
setIsLoading(false)
}
}
return (
<div>
{error && <div style={{ color: 'red' }}>{error}</div>}
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
</div>
)
}
(Source: Next.js Docs (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#error-handling))