pear-holder
pear-holder

Reputation: 13

How to get the formData of a very long long form

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?

Upvotes: 0

Views: 160

Answers (2)

pear-holder
pear-holder

Reputation: 13

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 ....
    };
}

Upvotes: 0

Stefan
Stefan

Reputation: 974

See https://developer.mozilla.org/en-US/docs/Web/API/FormData

I did not check the following code. Report, if it does what you want. Otherwise, you can always resort to the other FormData methods.

const plainObject = Object.fromEntries(formData.entries());

Upvotes: 0

Related Questions