Avoid Repeated Calls to FormData.get in Server Actions
Unanswered
VoidPointer posted this in #help-forum
I have a number of server actions that start out like this:
I'd like to do away with these repeated, hard-coded calls, and Gemini suggested using
//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, desc4 Replies
use
zod-form-datait validates your data and gives you a the usual and familiar
. api and type safetyThanks, but I've replacd the z schema with a zfd schema, and am now stuck on this choice:
If I uncomment
//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 resulteditCategorySchema.parse works nicely with no errors