---
title: "Transactions"
framework: javascript
version: "14.1.0"
---

# Transactions

Efficiently update chart data using incremental transactions without replacing the entire dataset. Use Transaction Updates for fast changes to large datasets.

## Apply Transaction API

The `applyTransaction()` method allows incrementally updating the chart data without replacing the entire dataset. It returns a Promise that resolves once the transaction has been applied and rendered.

## Transaction Operations

Transactions support three types of operations: adding, removing, and updating data items. Multiple operations can be combined in a single transaction.

#### Apply Transaction

```ts
import {
  AgChartOptions,
  AgCharts,
  BarSeriesModule,
  CategoryAxisModule,
  ModuleRegistry,
  NumberAxisModule,
} from "ag-charts-community";
import { random } from "./seededRandom";

interface DataItem {
  category: string;
  value: number;
}

let nextId = 1;
function createItem(): DataItem {
  return {
    category: `Item ${nextId++}`,
    value: Math.round(random() * 100),
  };
}
function getInitialData(): DataItem[] {
  const items: DataItem[] = [];
  for (let i = 0; i < 20; i++) {
    items.push(createItem());
  }
  return items;
}
const data: DataItem[] = getInitialData();
ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  NumberAxisModule,
]);

const options: AgChartOptions = {
  data,
  series: [
    {
      type: "bar",
      xKey: "category",
      yKey: "value",
    },
  ],
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);

function addItems() {
  const newItems: DataItem[] = [];
  for (let i = 0; i < 5; i++) {
    newItems.push(createItem());
  }
  data.push(...newItems);
  chart.applyTransaction({ add: newItems });
}

function addAtIndex() {
  const newItem = createItem();
  const insertIndex = Math.min(2, data.length);
  data.splice(insertIndex, 0, newItem);
  chart.applyTransaction({ add: [newItem], addIndex: 2 });
}

function removeItem() {
  if (data.length === 0) return;
  const itemToRemove = data.pop()!;
  chart.applyTransaction({ remove: [itemToRemove] });
}

function updateItems() {
  if (data.length === 0) return;
  const itemsToUpdate = data.slice(0, Math.min(5, data.length));
  for (const item of itemsToUpdate) {
    item.value = Math.round(random() * 100);
  }
  chart.applyTransaction({ update: itemsToUpdate });
}

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).addItems = addItems;
  (<any>window).addAtIndex = addAtIndex;
  (<any>window).removeItem = removeItem;
  (<any>window).updateItems = updateItems;
}
```

[Live example: Apply Transaction](https://www.ag-grid.com/charts/typescript/transactions/examples/simple-apply-transaction)

- **Add 5 Items**: Appends 5 new items to the end of the dataset.
- **Add at Index 2**: Inserts a new item at position 2 using `addIndex`.
- **Remove Last**: Removes the last item from the dataset.
- **Update First 5**: Modifies the values of the first 5 items.

> **Note**
>
> By default, items are identified by object reference. To update or remove an item, you must pass the same object instance that exists in the data array.
>
> Alternatively, set `dataIdKey` to identify items by a unique field instead. See [Identifying Items by Key](#identifying-items-by-key) below.

### Adding Data

Use the `add` property to append new data items to the dataset.

```js
// Add new items to the end
chart.applyTransaction({
    add: [
        { category: 'Item 1', value: 42 },
        { category: 'Item 2', value: 38 },
    ],
});
```

Use `addIndex` to control where items are inserted:

```js
// Add item to the beginning
chart.applyTransaction({
    add: [{ category: 'Item 0', value: 50 }],
    addIndex: 0,
});

// Add item at a specific position
chart.applyTransaction({
    add: [{ category: 'Item 3', value: 45 }],
    addIndex: 2,
});
```

### Removing Data

Use the `remove` property to remove items from the dataset.

Items are matched by referential equality, meaning you must provide the exact object reference that exists in the data array.

```js
// Keep a reference to the data items
const data = [
    { category: 'Item 1', value: 50 },
    { category: 'Item 2', value: 55 },
    { category: 'Item 3', value: 45 },
];

// Later, remove specific items by reference
const itemToRemove = data[0];
chart.applyTransaction({
    remove: [itemToRemove],
});
```

### Updating Data

Use the `update` property to modify existing items.

First mutate the item in place, then pass the reference in the transaction.

```js
// Keep a reference to the data items
const data = [
    { category: 'Item 1', value: 50 },
    { category: 'Item 2', value: 55 },
];

// Mutate the item in place
const itemToUpdate = data[1];
itemToUpdate.value = 100;

// Notify the chart of the change
chart.applyTransaction({
    update: [itemToUpdate],
});
```

### Combined Operations

Multiple operations can be performed in a single transaction for efficiency.

```js
chart.applyTransaction({
    remove: [oldItems[0], oldItems[1]],
    update: [modifiedItem],
    add: [
        { category: 'Item 10', value: 62 },
        { category: 'Item 11', value: 58 },
    ],
});
```

Operations are processed in order: add, then remove, then update.

## Identifying Items by Key

Set the `dataIdKey` chart option to a property name on your data items to identify them by that field instead of by object reference.

When `dataIdKey` is set:

- **Remove** operations only need the ID field on each item.
- **Update** operations match by ID and replace the existing datum with the new object.
- **Add** operations work the same as without `dataIdKey`.

`dataIdKey` also determines the `itemId` exposed in many node events and states. See [Item Identifiers](https://www.ag-grid.com/charts/javascript/events/#item-identifiers) for more details.

#### ID-Based Transaction

```ts
import {
  AgChartOptions,
  AgCharts,
  BarSeriesModule,
  CategoryAxisModule,
  ModuleRegistry,
  NumberAxisModule,
} from "ag-charts-community";
import { random } from "./seededRandom";

interface DataItem {
  id: string;
  category: string;
  value: number;
}

let nextId = 1;
function createItem(): DataItem {
  const id = `item-${nextId}`;
  return {
    id,
    category: `Item ${nextId++}`,
    value: Math.round(random() * 100),
  };
}
function getInitialData(): DataItem[] {
  const items: DataItem[] = [];
  for (let i = 0; i < 20; i++) {
    items.push(createItem());
  }
  return items;
}
const data: DataItem[] = getInitialData();
ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  NumberAxisModule,
]);

const options: AgChartOptions = {
  dataIdKey: "id",
  data,
  series: [
    {
      type: "bar",
      xKey: "category",
      yKey: "value",
    },
  ],
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);

function addItems() {
  const newItems: DataItem[] = [];
  for (let i = 0; i < 3; i++) {
    newItems.push(createItem());
  }
  data.push(...newItems);
  chart.applyTransaction({ add: newItems });
}

function removeById() {
  if (data.length === 0) return;
  const lastItem = data.pop()!;
  // Only need the ID field to remove
  chart.applyTransaction({ remove: [{ id: lastItem.id } as any] });
}

function updateById() {
  if (data.length === 0) return;
  // Create a brand-new object with the same ID
  const existing = data[0];
  const replacement: DataItem = {
    id: existing.id,
    category: existing.category,
    value: Math.round(random() * 100),
  };
  data[0] = replacement;
  chart.applyTransaction({ update: [replacement] });
}

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).addItems = addItems;
  (<any>window).removeById = removeById;
  (<any>window).updateById = updateById;
}
```

[Live example: ID-Based Transaction](https://www.ag-grid.com/charts/typescript/transactions/examples/id-based-transaction)

- **Add 3 Items**: Appends 3 new items to the dataset.
- **Remove Last by ID**: Removes the last item using only its `id` field.
- **Update First by ID**: Creates a new object with the same `id` to replace the first item.

### Setting dataIdKey

```js
const options = {
    dataIdKey: 'id',
    data: [
        { id: 'item-1', category: 'Category A', value: 42 },
        { id: 'item-2', category: 'Category B', value: 58 },
    ],
    // ...
};
```

The values of the `dataIdKey` field must be unique strings or numbers across the dataset.

### Removing by ID

When `dataIdKey` is set, remove items by passing objects containing only the ID field:

```js
chart.applyTransaction({
    remove: [{ id: 'item-1' }],
});
```

### Updating by ID

Pass a new object with the matching ID. The existing datum is fully replaced:

```js
chart.applyTransaction({
    update: [{ id: 'item-2', category: 'Category B', value: 99 }],
});
```

Unlike reference-based updates where you mutate the original object, ID-based updates use replacement semantics — the chart stores the new object in place of the old one.

## API Reference

#### Transaction Interface

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| add | unknown[] |  | Data items to add to the dataset.  Use `addIndex` to control the insertion position, otherwise items are appended to the end. |
| addIndex | number |  | Zero-based index at which to insert the `add` items. - If undefined or >= dataset length: items are appended to the end - If 0: items are prepended to the beginning - Otherwise: items are inserted at the specified position |
| remove | unknown[] |  | Data items to remove from the dataset.  Items are matched by referential equality (object reference). When `dataIdKey` is set on the chart, only the ID field is needed on each item. |
| update | unknown[] |  | Data items to update in the dataset.  Items are matched by referential equality (object reference). When `dataIdKey` is set on the chart, items are matched by the ID field and the existing datum is replaced entirely by the new object. |

#### Chart Instance

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| applyTransaction (required) | Function |  | Apply a transaction to incrementally update the chart data without replacing the entire dataset.  Returns a `Promise` that resolves once the transaction has been applied and rendered |

#### Chart Options

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| dataIdKey | DatumKey |  | The key of the property on each datum that contains its unique identifier. When specified, transactions will match items by this field instead of by object reference. The values of this field must be unique across the dataset. |
