Skip to content
This repository was archived by the owner on Nov 6, 2023. It is now read-only.
/ safe-actions Public archive

Safe actions for NextJS server actions using Zod.

License

Notifications You must be signed in to change notification settings

thoo0224/safe-actions

Repository files navigation

Safe Actions

Safe actions with zod and revalidation for server actions in Next.JS

This lib is dead and this one is much better:

https://next-safe-action.dev/

Installation

pnpm add @thoo0224/safe-actions zod
yarn add @thoo0224/safe-actions zod
npm install @thoo0224/safe-actions zod

Get Started

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

Contribution

Any type of contribution is greatly appreciated!

About

Safe actions for NextJS server actions using Zod.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published