Provides helper functions to define a type-safe React server action for forms, validating form data with Zod and handling errors internally.
To install this package
npm install @omer-x/next-form-actions"use server";
import { defineFormAction, displayMessage } from "@omer-x/next-form-actions";
import z from "zod";
import { authMiddleware } from "./middlewares/session";
export const createUser = defineFormAction({
middlewares: [authMiddleware],
schema: z.object({
foo: z.string(),
}),
action: input => (async () => {
console.log(input); // { foo: "bar" }
try {
// try to create a user
displayMessage("success", "ok!");
} catch (error) {
if (error === "BAD_REQUEST") {
displayMessage("warning", "you are doing something wrong");
}
displayMessage("error", "unknown error");
}
}),
});This project is licensed under the MIT License. See the LICENSE file for details.