I'm currently working with a very long form in NextJS, i have known about the server action recently and trying to do something about form and mutate data with it,it just give some example about handle server action like:
const handleCreate = async (formData: FormData) => {
"use server";
const rawFormData = {
id: formData.get("id"),
};
// Send rawFormData and do something ....
};
But the problem is when i have a very long form, how can i make the rawFormData without doing something like:
const rawFormData = {
id: formData.get("id"),
name: formData.get("name"),
address: formData.get("address"),
gender: formData.get("gender"),
// many many fields
dob: formData.get("dob"),
};
I have tried a dummy approach by passing an array of fields in the form and doing like this
const handleCreate = async (formData: FormData,fields: any[]) => {
"use server";
let rawFormData: any = {};
fields.forEach((field: any) => (rawFormData[field] = formData.get(field)));
// Fetch and do something ....
};
But it leading to another error say that NextJS does not allow to pass anything into action except formData How can i solve this problem?
I have try refreshing and doing something and finally find a way to do that by passing the props to the parent component and then pass it to the children like this:
const ParentComponent = ({fields}:{field:any[]}) => {
const handleCreate = async (formData: FormData) => {
"use server";
let rawFormData: any = {};
fields.forEach((field: any) => (rawFormData[field] = formData.get(field)));
// Fetch and do something ....
};
}