# Data States Pattern

Every component that consumes asynchronous data MUST handle four states.

---

## The Four Required States

| State | Condition | Expected UI |
|-------|-----------|-------------|
| **Loading** | `isLoading && !data` | Contextual skeleton or spinner |
| **Error** | `isError` | Error message + retry action |
| **Empty** | `!isLoading && data?.length === 0` | Informative message + optional call to action |
| **Success** | `data?.length > 0` | Normal rendering of the data |

---

## Incorrect (handles only success)

```tsx
function AccountsList() {
  const { data } = useAccounts();

  // Crashes if data is undefined
  // Shows no loading state
  // Does not handle errors
  return (
    <ul>
      {data.map(account => (
        <li key={account.id}>{account.name}</li>
      ))}
    </ul>
  );
}
```

---

## Correct (handles the four states)

```tsx
import { LoadingState, EmptyState, ErrorState } from '@/shared/ui';

function AccountsList() {
  const { t } = useTranslation();
  const { data, isLoading, isError, refetch } = useAccounts();

  // 1. Loading
  if (isLoading) {
    return <LoadingState variant="list" items={3} />;
  }

  // 2. Error
  if (isError) {
    return (
      <ErrorState
        message={t('accounts.error')}
        onRetry={refetch}
      />
    );
  }

  // 3. Empty
  if (!data?.length) {
    return (
      <EmptyState
        message={t('accounts.empty')}
        icon="CreditCard"
      />
    );
  }

  // 4. Success
  return (
    <ul>
      {data.map(account => (
        <li key={account.id}>{account.name}</li>
      ))}
    </ul>
  );
}
```

---

## Using DDataStateWrapper (recommended)

`DDataStateWrapper` renders loading, error or empty, in that order, and hands the data to its children when there is any. The three state components come from `@/shared/ui`:

```tsx
import { DDataStateWrapper } from '@dynamic-framework/ui-react';
import { EmptyState, ErrorState, LoadingState } from '@/shared/ui';

function AccountsList() {
  const { t } = useTranslation();
  const { data, isLoading, isError, refetch } = useAccounts();

  return (
    <DDataStateWrapper
      isLoading={isLoading}
      isError={isError}
      data={data}
      onRetry={refetch}
      renderLoading={<LoadingState variant="list" items={5} />}
      renderEmpty={<EmptyState message={t('accounts.empty')} />}
      renderError={<ErrorState message={t('accounts.error')} onRetry={refetch} />}
    >
      {(accounts) => (
        <ul>
          {accounts.map(account => (
            <li key={account.id}>{account.name}</li>
          ))}
        </ul>
      )}
    </DDataStateWrapper>
  );
}
```

---

## State Components

### LoadingState

```tsx
<LoadingState variant="spinner" />        // Centered spinner
<LoadingState variant="list" items={5} /> // List skeleton
<LoadingState variant="card" />           // Card skeleton
<LoadingState variant="table" rows={3} /> // Table skeleton
```

### ErrorState

```tsx
<ErrorState
  message={t('accounts.error')}   // Optional - defaults to the translated generic error
  onRetry={refetch}               // Optional - shows a retry button
  color="danger"                  // Optional - 'danger' (default) or 'warning'
/>
```

### EmptyState

```tsx
<EmptyState
  message={t('accounts.empty')}   // Optional - defaults to the translated generic message
  icon="FileText"                 // Optional - Lucide icon
  actionText={t('accounts.new')}  // Optional - call-to-action text
  onAction={handleCreate}         // Optional - call-to-action handler
/>
```

---

## Implementation Checklist

- [ ] Does the component use a hook that returns `isLoading`?
  - Yes -> it MUST check `isLoading` before rendering data
- [ ] Can the hook fail (API call)?
  - Yes -> it MUST check `isError` and show `ErrorState`
- [ ] Is the data an array?
  - Yes -> it MUST check `length === 0` and show `EmptyState`
- [ ] Is there appropriate visual feedback for each state?

---

## Anti-patterns to Avoid

### Generic loading without context

```tsx
// Bad: gives no context about what is loading
if (isLoading) return <DSpinner />;
```

### Contextual loading

```tsx
// Good: skeleton that mirrors the final structure
if (isLoading) return <LoadingState variant="list" items={3} />;
```

### Error without an action

```tsx
// Bad: the user can do nothing
if (isError) return <p>Error</p>;
```

### Error with retry

```tsx
// Good: the user can try again
if (isError) return <ErrorState message={t('accounts.error')} onRetry={refetch} />;
```

### Invisible empty state

```tsx
// Bad: renders nothing, the user is confused
if (!data?.length) return null;
```

### Informative empty state

```tsx
// Good: explains the situation
if (!data?.length) return <EmptyState message={t('accounts.empty')} />;
```

---

## Error Boundaries

Data states handle **expected** errors (a failed API call, empty data). Error boundaries handle **unexpected** errors (bugs, crashes).

### Difference

| Type | Cause | Handling |
|------|-------|----------|
| Expected error | The API returns a 500 | `isError` -> `ErrorState` |
| Unexpected error | A bug in the code, an access to `undefined` | `ErrorBoundary` -> fallback UI |

### Usage

```tsx
// App.tsx
<QueryProvider>
  <ErrorBoundary>
    <MainWidget />  {/* If MainWidget crashes, ErrorBoundary catches it */}
  </ErrorBoundary>
</QueryProvider>
```

### ErrorBoundary with external logging

```tsx
<ErrorBoundary
  onError={(error, errorInfo) => {
    // Send to your error-reporting service
    reportError(error, { extra: errorInfo });
  }}
>
  <MainWidget />
</ErrorBoundary>
```

`ErrorBoundary` is exported from `@/shared/ui` (`src/shared/ui/ErrorBoundary.tsx`), where it re-exports `DErrorBoundary` from `@dynamic-framework/ui-react`. Its `fallback` receives `{ error, resetErrorBoundary }`.

---

## See Also

- `modyo://docs/widgets/patterns-tanstack-query`
- `modyo://docs/widgets/patterns-utilities`
- `modyo://docs/widgets/reference-ui-patterns`
