Next.js Discord

Discord Forum

Avoid Repeated Calls to FormData.get in Server Actions

Unanswered
VoidPointer posted this in #help-forum
Open in Discord
I have a number of server actions that start out like this:
  //const values = Object.fromEntries(formData.entries());
  const values = {
    id: formData.get("id") as unknown as number,
    name: formData.get("name") as string,
    desc: formData.get("desc") as string,
  };

I'd like to do away with these repeated, hard-coded calls, and Gemini suggested using fromEntries but that gives me this error:
Type '{ [k: string]: FormDataEntryValue; }' is missing the following properties from type '{ id: number; name: string; desc: string; }': id, name, desc

4 Replies

use zod-form-data
it validates your data and gives you a the usual and familiar . api and type safety
Thanks, but I've replacd the z schema with a zfd schema, and am now stuck on this choice:
  //const values = editCategorySchema.parse(formData);
  const result = editCategorySchema.safeParse(formData);
...
  if (!result.success) {
    return {
      values,
      success: false,
      errors: z.flattenError(result.error).fieldErrors,
    };
  }

If I uncomment const values, and submit to cause an error, then editCategorySchema.parse throws. And where i'm stuck is on trying to build a values from result
editCategorySchema.parse works nicely with no errors