# Async Actions Pattern

import { Callout } from "fumadocs-ui/components/callout";
import { Tabs, Tab } from "fumadocs-ui/components/tabs";
import { Steps, Step } from "fumadocs-ui/components/steps";
import { Badge, Card, CardHeader, CardTitle, CardContent } from "@pycolors/ui";
import { CheckCircle, Bell, FormInput, LoaderCircle, MessageSquareWarning, RefreshCw, RotateCcw, ShieldAlert, XCircle, Zap } from "lucide-react";
import { PreferAvoid } from '@/components/docs/prefer-avoid';
import { DocsLinks } from "@/components/docs/docs-links";
import { DocsFeatureGrid } from "@/components/docs/docs-feature-grid";
import { DocsConceptTabs } from "@/components/docs/docs-concept-tabs";

import {
  OptimisticToggleDemo,
  DeleteWithUndoToastDemo,
  SaveWithToastDemo,
} from "../previews/async-actions";

<div className="flex flex-wrap items-center gap-2">
  <Badge variant="outline">
    Patterns
  </Badge>

  <Badge>
    Async actions
  </Badge>
</div>

## Overview

Async actions are where product quality becomes visible.

Unlike data fetching, actions **change reality**:

* saving data
* deleting content
* triggering business logic
* updating user state

This guide defines how to handle mutations in a way that feels:

* fast
* reliable
* understandable
* production-ready

<Callout title="Key principle">
  Loading is about waiting.
  Actions are about trust.
</Callout>

## What you’ll implement

<DocsFeatureGrid
  columns={3}
  tone="platform"
  items={[
  {
    title: 'Immediate feedback',
    description:
      'Respond instantly to user actions without blocking the workflow.',
    icon: Zap,
  },
  {
    title: 'Correct feedback level',
    description:
      'Choose inline, toast, or blocking feedback depending on user risk.',
    icon: MessageSquareWarning,
  },
  {
    title: 'Recovery strategies',
    description:
      'Support retry, undo, and resilient recovery flows for safer UX.',
    icon: RotateCcw,
  },
]}
/>

### Mental model

> Actions should feel instant
> Errors should feel recoverable
> Nothing should feel broken

## Steps

<Steps>
  <Step>
    ### Choose optimistic vs pessimistic

    Not all actions should behave the same.

    #### Use optimistic UI when

    * toggles (enable / disable)
    * starring / favoriting
    * reversible updates

    #### Use pessimistic UI when

    * payments
    * destructive irreversible actions
    * permission-sensitive changes

    <OptimisticToggleDemo />

    <Callout type="info" title="Rule">
      If you can safely undo it → optimistic
      If you cannot → wait for server confirmation
    </Callout>
  </Step>

  <Step>
    ### Apply the right feedback tier

    Not every action deserves the same UX weight.

    <DocsConceptTabs
      items={[
  {
    value: 'Inline',
    title: 'Inline feedback',
    icon: FormInput,
    description: (
      <>
        <p>
          Inline feedback keeps users in flow and close to the affected element.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Button state</Badge>
          <Badge variant="outline">Inline messages</Badge>
          <Badge variant="outline">Subtle feedback</Badge>
          <Badge variant="outline">Low-risk actions</Badge>
        </div>
      </>
    ),
  },
  {
    value: 'Toast',
    title: 'Toast feedback',
    icon: Bell,
    description: (
      <>
        <p>
          Toasts communicate short-lived system feedback without interrupting the workflow.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Non-blocking</Badge>
          <Badge variant="outline">Undo</Badge>
          <Badge variant="outline">Retry</Badge>
          <Badge variant="outline">Background actions</Badge>
        </div>
      </>
    ),
  },
  {
    value: 'Blocking',
    title: 'Blocking feedback',
    icon: ShieldAlert,
    description: (
      <>
        <p>
          Blocking feedback requires explicit confirmation before continuing.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Confirmation dialog</Badge>
          <Badge variant="outline">Destructive actions</Badge>
          <Badge variant="outline">Irreversible changes</Badge>
          <Badge variant="outline">High-risk flows</Badge>
        </div>
      </>
    ),
  },
]}
    />

    <SaveWithToastDemo />

    <br />
  </Step>

  <Step>
    ### Design retry and undo flows

    Recovery is part of the UX.

    #### Retry

    * must be explicit
    * must be safe
    * must be idempotent

    #### Undo

    * works best for destructive actions
    * requires real backend support
    * should be immediate

    <DeleteWithUndoToastDemo />

    <Callout title="Important">
      Undo is not a UI trick.
      It must be supported by your backend logic.
    </Callout>
  </Step>
</Steps>

## Feedback tiers

| Level  | When to use                          |
| ------ | ------------------------------------ |
| Inline | expected, local changes              |
| Toast  | non-blocking confirmation or failure |
| Dialog | destructive or irreversible actions  |

Never mix roles.

### Error messaging

Good error messages:

* explain what failed
* suggest what to do next
* stay calm and clear

### Examples

<PreferAvoid
  preferTitle="Good"
  avoidTitle="Bad"
  prefer={[
  '“Couldn’t save changes. Check your connection and retry.”',
  '“Payment failed. Try another card.”',
]}
  avoid={[
  '“Something went wrong”',
  '“Unknown error”',
]}
/>

<Callout type="info" title="Rule">
  Always include: what failed + what to do next
</Callout>

## Common patterns

### Save flow

* inline loading state
* toast success or error
* retry on failure

### Delete flow

* confirmation dialog
* toast with undo
* retry if restore fails

### Toggle flow

* instant UI change
* rollback on error
* toast feedback

## Decision guide

<PreferAvoid
  prefer={[
  'instant feedback over spinners',
  'clear recovery paths',
  'consistent feedback levels',
  'optimistic updates when safe',
]}
  avoid={[
  'blocking UI for low-risk actions',
  'silent failures',
  'no retry or undo path',
  'inconsistent feedback patterns',
]}
/>

### Why this matters

Async actions are one of the biggest trust signals in a product.

Bad mutation UX leads to:

* hesitation
* repeated clicks
* confusion
* lost confidence

Good mutation UX feels:

* fast
* predictable
* safe

That is where products start to feel **production-ready**.

## Next steps

<DocsLinks
  variant="grid"
  tone="platform"
  items={[
  {
    title: 'Forms with validation',
    href: '/docs/guides/forms-with-validation',
    description:
      'Apply async patterns to real user input flows.',
    icon: FormInput,
  },
  {
    title: 'Async states',
    href: '/docs/guides/empty-loading-error',
    description:
      'Handle loading, empty, and error states consistently.',
    icon: LoaderCircle,
  },
]}
/>