# Load pivot data from an API or CSV

> Fetch records from a JSON API or a CSV export, clean them with parseCsv or csvToRecords, and load them into Pivot Studio with loading and error states.

Pivot Studio never fetches data itself: you hand it records or text. This recipe loads work orders from a JSON endpoint, falls back to a nightly CSV export, fixes the column types and date formats that automatic detection gets wrong, and shows loading and error states.

## Steps

1. Create the studio with an empty array and a saved report.
2. Fetch the data with an `AbortController`, so a second request cancels the first.
3. For CSV, parse it with `csvToRecords()` and force the types of code columns.
4. Convert dates that are not ISO, such as `14/03/2026`, before loading.
5. Call `setData(records)` and report the row count from `dataLoaded`.

## Fetch and load

```ts title="work-order-pivot.ts"
import { createPivotStudio, csvToRecords, type PivotReport } from '@birchui/pivot-studio';

interface WorkOrder {
  orderNo: string;
  depot: string;
  technician: string;
  jobType: string;
  completedOn: string;
  hours: number;
  revenue: number;
}

const report: PivotReport = {
  slice: {
    rows: [{ field: 'depot' }, { field: 'technician' }],
    columns: [{ field: 'completedOn.quarter' }],
    values: [{ field: 'revenue', aggregation: 'sum' }, { field: 'hours', aggregation: 'sum' }],
  },
  formats: { revenue: { style: 'currency', currency: 'GBP', decimals: 0 } },
};

const status = document.querySelector<HTMLElement>('#pivot-status')!;
const studio = createPivotStudio<WorkOrder>(document.querySelector<HTMLElement>('#work-order-pivot')!, {
  data: [],
  report,
  fields: [
    { name: 'orderNo', type: 'string', caption: 'Work order' },
    { name: 'completedOn', dateParts: ['year', 'quarter', 'month'] },
  ],
});

studio.on('dataLoaded', ({ rowCount }) => {
  status.textContent = `${rowCount.toLocaleString()} work orders loaded`;
});
studio.on('error', ({ message }) => {
  status.textContent = `${message}. The previous data is still shown.`;
});

let controller: AbortController | undefined;

export async function loadWorkOrders(from: string, to: string): Promise<void> {
  controller?.abort();
  controller = new AbortController();
  status.textContent = 'Loading work orders…';
  try {
    const response = await fetch(`/api/work-orders?from=${from}&to=${to}`, { signal: controller.signal });
    if (!response.ok) throw new Error(`The work order API returned ${response.status}`);
    studio.setData((await response.json()) as WorkOrder[]);
  } catch (error) {
    if ((error as Error).name === 'AbortError') return;
    await loadFromCsvExport();
  }
}
```

## Load a CSV export

`csvToRecords()` detects the delimiter, reads the header row and converts each column to its detected type. Pass `types` for columns that look numeric but are codes:

```ts title="csv-fallback.ts"
const UK_DATE = /^(\d{2})\/(\d{2})\/(\d{4})$/;

function toIsoDate(value: unknown): unknown {
  const match = typeof value === 'string' ? UK_DATE.exec(value) : null;
  return match ? `${match[3]}-${match[2]}-${match[1]}` : value;
}

async function loadFromCsvExport(): Promise<void> {
  const text = await fetch('/exports/work-orders-latest.csv').then((r) => r.text());
  const { records, columns, delimiter } = csvToRecords(text, {
    types: { orderNo: 'string', depotCode: 'string', completedOn: 'string' },
  });
  for (const record of records) record.completedOn = toIsoDate(record.completedOn);
  console.info(`Read ${records.length} rows with ${columns.length} columns, separated by "${delimiter}"`);
  studio.setData(records as unknown as WorkOrder[]);
}
```

`completedOn` is read as text first, so the conversion sees the original `dd/mm/yyyy` string; after `setData()` the ISO dates are detected as dates and get the year, quarter and month levels the report uses.

## Work with raw rows

When a file needs more cleanup than a type override, read it as rows with `parseCsv()`:

```ts title="parse-rows.ts"
import { parseCsv, sniffDelimiter } from '@birchui/pivot-studio';

const delimiter = sniffDelimiter(text);
const [header, ...rows] = parseCsv(text, { delimiter });
const hoursColumn = header.indexOf('Hours worked');

const records = rows
  .filter((row) => row[0] !== '' && !row[0].startsWith('Total'))
  .map((row) => ({
    orderNo: row[0],
    depot: row[1],
    technician: row[2],
    hours: Number(row[hoursColumn].replace(',', '.')),
  }));
```

This handles exports with summary rows at the bottom and decimal commas, which a plain type override cannot.

## Pass the text straight in

If the CSV is already clean, skip the parsing step: `setData(text)` accepts CSV and JSON text and uses the same parser.

```ts
studio.setData(await fetch('/exports/work-orders-latest.csv').then((r) => r.text()), { format: 'csv' });
```

## Pitfalls

- **Leading zeros.** Codes such as `007` stay text automatically, but codes without leading zeros, such as depot `1042`, are detected as numbers and summed. Force them to `'string'` with `types` or a field definition.
- **Dates in local notation.** Only ISO dates are detected as dates. Convert `dd/mm/yyyy` or `mm/dd/yyyy` text before loading.
- **Errors keep old data.** When text cannot be parsed, the widget keeps its previous data and fires `error`. Show the message so users know the view is stale.
- **Mutating records.** If you change record objects after loading, call `refresh()` so the widget re-reads them.

## Related

- [Data](https://docs.birchui.com/pivot-studio/data.md) for detection rules and [field definitions](https://docs.birchui.com/pivot-studio/data.md#field-definitions).
- [CSV parsing rules](https://docs.birchui.com/pivot-studio/data.md#csv).
- [Save and load pivot layouts](https://docs.birchui.com/recipes/pivot-saved-layouts.md).

**`CsvRecordsOptions`** (interface from `@birchui/pivot-studio`, full reference: https://docs.birchui.com/api/pivot-studio.md)

```ts
interface CsvRecordsOptions
```

| Property | Type | Description |
| --- | --- | --- |
| `delimiter?` | `string` |  |
| `header?` | `boolean` |  |
| `types?` | `Record<string, FieldType>` |  |
| `limits?` | `Partial<DataLimits>` |  |
