# Loading, empty and errors

Four states in every card, all driven by the results prop.

The samples assume the `ChartsProvider` from [step 2 of the quick start](/docs/quick-start.md#2-add-the-provider).

A card draws one of four states from its `results` prop. There is nothing else to wire: pass the state of your request straight through.

## The four states

```tsx title="ChartStates.tsx"
import { BarChart, dimension, measure, results } from 'em-kit';

const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({ name: 'customers', title: 'Customers' });

const rows = [
  { plan: 'Starter', customers: 1840 },
  { plan: 'Growth', customers: 920 },
  { plan: 'Enterprise', customers: 140 },
];

const grid = {
  display: 'grid',
  gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
  gridAutoRows: 280,
  gap: 16,
};

export function ChartStates() {
  const fields = { dimension: plan, measures: [customers] };
  return (
    <div style={grid}>
      <BarChart title="Loading" {...fields} results={{ isLoading: true }} />
      <BarChart title="Refreshing" {...fields} results={{ isLoading: true, data: rows }} />
      <BarChart title="Empty" {...fields} results={results([])} />
      <BarChart
        title="Error"
        {...fields}
        results={{ isLoading: false, error: 'The query timed out after 30 seconds.' }}
      />
    </div>
  );
}
```

Result: four cards showing a skeleton, a chart with a spinner in its header, “No results.” and “Something went wrong.”

| Value of results | The card shows |
|---|---|
| `{ isLoading: true }` | A skeleton. |
| `{ isLoading: true, data: rows }` | The chart it already has, with a spinner in the header. |
| `{ isLoading: false, data: [] }` | The empty state. |
| `{ isLoading: false, error: 'message' }` | The error state, with your message. |

The empty and error headings are translated with the rest of the built-in text: see [Localisation](/docs/localisation.md).

## From a request to results

The components never fetch, so something has to turn your request into that shape. This hook does it for any function that returns a promise of rows: a skeleton first, the rows when they arrive, and the message of the error if the request fails.

```tsx title="RevenueFromApi.tsx"
import { useEffect, useState } from 'react';
import { BarChart, dimension, measure, type DataResponse } from 'em-kit';

// Turns a function that returns a promise of rows into the `results` a card
// takes. `deps` are the values the request depends on, such as filters.
type Rows = DataResponse['data'];

export function useResults(load: () => Promise<Rows>, deps: unknown[]): DataResponse {
  const [state, setState] = useState<DataResponse>({ isLoading: true });

  useEffect(() => {
    let current = true;
    // The rows already on screen stay while the next ones load.
    setState((previous) => ({ isLoading: true, data: previous.data }));
    load().then(
      (data) => current && setState({ isLoading: false, data }),
      (error: unknown) => {
        const message = error instanceof Error ? error.message : String(error);
        if (current) setState({ isLoading: false, error: message });
      },
    );
    return () => {
      current = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  return state;
}

const plan = dimension({ name: 'plan', title: 'Plan' });
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 0 },
});

// Your data layer: anything that resolves to rows, or rejects with an Error.
// This one stands in for a request that takes a moment.
const rows = [
  { region: 'Europe', plan: 'Starter', revenue: 18400 },
  { region: 'Europe', plan: 'Team', revenue: 42900 },
  { region: 'Americas', plan: 'Starter', revenue: 21700 },
  { region: 'Americas', plan: 'Team', revenue: 38100 },
];
const fetchRevenueByPlan = (region: string) =>
  new Promise<typeof rows>((resolve) => {
    setTimeout(() => resolve(rows.filter((row) => row.region === region)), 600);
  });

export function RevenueFromApi({ region = 'Europe' }: { region?: string }) {
  const results = useResults(() => fetchRevenueByPlan(region), [region]);
  return (
    <BarChart title="Revenue by plan" dimension={plan} measures={[revenue]} results={results} />
  );
}
```

With a data library you already have the three values. For TanStack Query: `results={{ isLoading: query.isPending, data: query.data, error: query.error?.message }}`.
