Skip to content

NarixHine/uni-chem / .agents/skills/safe-action-hooks

safe-action-hooks

Verified

Use when executing next-safe-action actions from React client components -- useAction, useOptimisticAction, handling status/callbacks (onSuccess/onError/onSettled), execute vs executeAsync, or optimistic UI updates

FileKindSize
SKILL.mdskill md6.5 KB
optimistic-updates.mdmarkdown3.0 KB
status-callbacks.mdmarkdown5.2 KB
throw-on-navigation.mdmarkdown4.5 KB
use-action.mdmarkdown4.2 KB
use-state-action.mdmarkdown7.3 KB

use-action.md

View on GitHub
# execute vs executeAsync

## execute — Fire and Forget

`execute(input)` triggers the action and updates hook state reactively. It does not return a value — use callbacks or `result` to react to the outcome.

```tsx
const { execute, result, isPending } = useAction(myAction, {
  onSuccess: ({ data }) => {
    toast.success("Done!");
    router.refresh();
  },
  onError: ({ error }) => {
    toast.error(error.serverError ?? "Something went wrong");
  },
});

// Trigger
<button onClick={() => execute({ name: "Alice" })}>Submit</button>
```

Internally, `execute` runs inside `React.startTransition` with a `setTimeout(0)` for deferred state updates.

## executeAsync — Awaitable Result

`executeAsync(input)` returns a `Promise<SafeActionResult>`. Useful when you need the result inline (e.g., in a multi-step flow).

```tsx
const { executeAsync, isPending } = useAction(myAction);

const handleSubmit = async () => {
  const result = await executeAsync({ name: "Alice" });

  if (result.data) {
    // Navigate, show toast, etc.
    router.push(`/users/${result.data.id}`);
  }
  if (result.serverError) {
    toast.error(result.serverError);
  }
};
```

**Important:** If the action triggers a navigation error (redirect, notFound, etc.), `executeAsync` will **throw**. Always wrap in try/catch if your action might navigate:

```tsx
const handleSubmit = async () => {
  try {
    const result = await executeAsync(input);
    // Handle result...
  } catch (e) {
    // Navigation errors propagate to Next.js — rethrow them
    throw e;
  }
};
```

## Result Object

`result` is a **discriminated union** with 4 mutually exclusive branches (no explicit `status` field — the discriminant is which of `data` / `serverError` / `validationErrors` is populated):

```ts
const { result } = useAction(myAction);

// Branches:
//   idle / cleared:     { data: undefined; serverError: undefined; validationErrors: undefined }
//   success:            { data: Data;      serverError: undefined; validationErrors: undefined }
//   server error:       { data: undefined; serverError: SE;        validationErrors: undefined }
//   validation error:   { data: undefined; serverError: undefined; validationErrors: VE         }
```

Checking any one field narrows the other two to `undefined`:

```ts
if (result.data) {
  // result.serverError      → undefined
  // result.validationErrors → undefined
}
```

The result is the idle branch initially and after `reset()`. Precedence when multiple outcomes coexist: `validationErrors` > `serverError` > `data`.

## Type Narrowing via Hook Status

The hook return itself is a discriminated union keyed on `status` — so shorthand booleans work as type guards and narrow `result` directly, without checking `result.data` first:

```ts
const action = useAction(myAction);

if (action.hasSucceeded) {
  action.result.data;        // Data (guaranteed — not Data | undefined)
  action.result.serverError; // undefined
}

if (action.hasErrored) {
  // result.serverError or result.validationErrors is populated
}
```

The destructured form works the same way when keyed on `status`:

```ts
const { status, result } = useAction(myAction);
if (status === "hasSucceeded") {
  result.data; // narrowed to Data
}
```

For void-returning actions, `result.data` is typed as `undefined` (not `void | undefined`) thanks to `NormalizeActionResult`.

## Sequential Actions

Use `executeAsync` for dependent calls:

```tsx
const uploadAction = useAction(uploadFile);
const createPostAction = useAction(createPost);

const handlePublish = async () => {
  const uploadResult = await uploadAction.executeAsync({ file });
  if (!uploadResult.data) return;

  const postResult = await createPostAction.executeAsync({
    title,
    imageUrl: uploadResult.data.url,
  });
  if (postResult.data) {
    router.push(`/posts/${postResult.data.id}`);
  }
};
```

## reset()

Resets the hook to its initial state — clears result, input, status, and sets `isIdle` to `true`.

```tsx
const { execute, result, reset } = useAction(myAction);

// After showing a success message
useEffect(() => {
  if (result.data) {
    const timer = setTimeout(reset, 3000);
    return () => clearTimeout(timer);
  }
}, [result.data, reset]);
```
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall