pnpm add @thoo0224/safe-actions zod
yarn add @thoo0224/safe-actions zod
npm install @thoo0224/safe-actions zod
Create the action.
"use server";
import { safeAction } from "@thoo0224/safe-actions/server";
import { z } from "zod";
export const sendAlertAction = safeAction({
inputValidation: z.object({
from: z.string(),
alert: z.string(),
}),
action: async ({ from, alert }) => {
if(from === "Ethan") {
return {
failure: {
message: "Ethan can't send alerts!"
};
}
}
return {
message: `From: ${from}\nMessage: ${alert}`,
revalidate: true // This will call revalidatePath() on the revalidation paths if they are provided in the useSafeAction hook.
}
},
});
Use the action.
"use client";
import { useSafeAction } from "@thoo0224/safe-actions/client";
import { sendAlertAction } from "./actions";
export default function AlertForm() {
// When the action finishes successfully, it will revalidate [/, /somePath, /someOtherPath]
const { run, data, error, isRunning } = useSafeAction({
action: sendAlertAction,
persistData: true, // When false, `data` will be set to null before the action is ran. When true, `data` will only change if the action is finished.
revalidationPaths: ["/somePath", "/someOtherPaths"],
revalidateCurrentPath: true, // Revalidates the current path (`usePathname()`) Default: false
});
// OR
const { run, data, error, isRunning } = useSafeAction(sendAlertAction);
return (
<button
onClick={async () => {
const data2 = await run();
}}
>
Alert
</button>
);
}
Any type of contribution is greatly appreciated!