# Adding Rows to AG Grid

Canonical page: https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-add

- AdapTable provides an `addGridData` function to add rows to AG Grid
- This can be run synchronously or asynchronously

AdapTable facilitates adding rows to AG Grid, while the application is live.

This is done via the `addGridData` function in the [`Grid API`](https://www.adaptabletools.com/docs/reference/gridapi.md) section of [Adaptable API](https://www.adaptabletools.com/docs/technical-reference-adaptable-api/index.md).

- We strongly recommend **using this function** to add rows to AG Grid, rather than the AG Grid API directly
- The function ultimately calls an AG Grid function but first performs important checks (e.g. for [Primary Key](https://www.adaptabletools.com/docs/getting-started-primary-key/index.md))

This function can be run either synchronously or asynchronously as required.

There is an option to configure where in the Grid the row will be added

The `addGridData` function does 2 things:

- invokes AG Grid `applyTransaction` function (or `applyTransactionAsync` if called asynchronously)

- publishes the [Row Changed Event](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md) with a Trigger of `Add` (which will in turn trigger any [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md))

### `addGridData`

Adds new Rows to AG Grid (asynchronously if required)

Use this function to add any rows to AG Grid while your application is live (asynchronously if required).

The signature of the function is:

```ts
addGridData(dataRows: any[], config?: DataUpdateConfig): Promise<RowNode[]>;
```

As can be seen, it receives 2 arguments:

- an array of data rows
- an (optional) [`DataUpdateConfig`](https://www.adaptabletools.com/docs/reference/dataupdateconfig.md) object

and returns (via a Promise) the AG Grid [RowNodes](https://www.ag-grid.com/javascript-data-grid/row-object/) that were added.

When invoked the function does some internal checks and validation and then calls one of these 2 AG Grid functions:

- `applyTransaction` with param of `add` - if no async config was provided
- `applyTransactionAsync` - if a config object with `runAsync` set to _true_ was supplied

If the [Server-Side Row Model](https://www.adaptabletools.com/docs/dev-guide-row-models-server-updating/index.md) is being used, AdapTable calls `applyServerSideTransaction[Async]` instead

<b>DataUpdateConfig</b>

The [`DataUpdateConfig`](https://www.adaptabletools.com/docs/reference/dataupdateconfig.md) object is used to enable an asynchronous operation and to provide a callback if needed:

| Property | Type | Description |
| --- | --- | --- |
| [addIndex](https://www.adaptabletools.com/docs/reference/dataupdateconfig.md#addindex) | `number` | Index where to add new rows |
| [callback](https://www.adaptabletools.com/docs/reference/dataupdateconfig.md#callback) | `(res: any) => void` | Callback function invoked when a batch successfully concludes |
| [flushAsync](https://www.adaptabletools.com/docs/reference/dataupdateconfig.md#flushasync) | `boolean` | Whether to flush async operations |
| [runAsync](https://www.adaptabletools.com/docs/reference/dataupdateconfig.md#runasync) | `boolean` | Whether row operation should happen asynchronously |

- The `flushAsync` flag can be set to _true_ even if `runAsync` is _false_
- In other words, even if the current transaction is synchronous, this will still flush existing async transactions

Make sure all mandatory fields are included in the DataRow(s) provided, and that the Primary Key is unique

```ts {3,8}
// Add a new Trade to the Grid
const trade: ITrade = getTradeFromServer();
adaptableApi.gridApi.addGridData([trade]);

// Add a new Trade to AG Grid asynchronously
const trade: ITrade = getTradeFromServer();
const config: DataUpdateConfig = {runAsync: true};
adaptableApi.gridApi.addGridData([trade], config);
```

<b>addIndex</b>

The `addIndex` config property can be used, if required, to specify **where** in AG Grid the new rows should be added

```ts {4}
// Add a new Trade to the top of the Grid
const trade: ITrade = getTradeFromServer();
const config: DataUpdateConfig = {addIndex: 0};
adaptableApi.gridApi.addGridData([trade], config);
```

**Example: Adding Row Data**

Adding Rows to AG Grid at run-time

- This demo shows how to add rows in AG Grid at run-time using the `addGridData` function in Grid API

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableButton,
  AdaptableOptions,
  CustomToolbarButtonContext,
  DashboardButtonContext,
  DataUpdateConfig,
} from '@adaptabletools/adaptable';
import {rowData, WebFramework} from './rowData';

export function createPython(): WebFramework {
  return {
    id: Math.floor(Math.random() * (1000000 - 5000 + 1) + 200000),
    name: 'python',
    description: 'A very popular language.',
    created_at: new Date().toDateString(),
    updated_at: new Date().toDateString(),
    pushed_at: new Date().toDateString(),
    github_stars: 5000,
    language: 'Python',
    open_issues_count: 750,
    license: 'MIT License',
    github_watchers: 6671,
    topics: ['duck typing', 'proxies', 'prerformance', 'solid'],
    has_projects: true,
    has_wiki: true,
    has_pages: false,
    closed_issues_count: 12326,
    open_pr_count: 749,
    closed_pr_count: 1708,
    week_issue_change: 15,
  };
}

export function createGo(): WebFramework {
  return {
    id: Math.floor(Math.random() * (1000000 - 5000 + 1) + 200000),
    name: 'go',
    description: 'A very popular language.',
    created_at: new Date().toDateString(),
    updated_at: new Date().toDateString(),
    pushed_at: new Date().toDateString(),
    github_stars: 3850,
    language: 'Go',
    open_issues_count: 837,
    license: 'BSD 3-Clause',
    github_watchers: 9852,
    topics: ['open sournce', 'similar to C'],
    has_projects: true,
    has_wiki: true,
    has_pages: false,
    closed_issues_count: 10254,
    open_pr_count: 985,
    closed_pr_count: 2014,
    week_issue_change: 65,
  };
}

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Adding Grid Rows',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'ButtonToolbar',
        title: 'Buttons',
        toolbarButtons: [
          {
            label: 'Add Python Row to Top',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const python: WebFramework = createPython();
              const dataUpdateConfig: DataUpdateConfig = {
                runAsync: true,
                addIndex: 0,
              };
              context.adaptableApi.gridApi.addGridData(
                [python],
                dataUpdateConfig
              );
            },
            buttonStyle: {
              tone: 'info',
              variant: 'text',
            },
            disabled: () => false,
          },
          {
            label: 'Add Go Row',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const go: WebFramework = createGo();
              const dataUpdateConfig: DataUpdateConfig = {
                runAsync: true,
              };
              context.adaptableApi.gridApi.addGridData([go], dataUpdateConfig);
            },
            buttonStyle: {
              tone: 'warning',
              variant: 'text',
            },
            disabled: () => false,
          },
        ],
      },
    ],
  },
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Dashboard: {
      PinnedToolbars: ['ButtonToolbar'],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'created_at',
            'has_wiki',
            'github_watchers',
            'updated_at',
            'pushed_at',
            'description',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-row-added',
          Rule: 'ROW_ADDED{}',
          MessageType: 'Success',
          Scope: {
            All: true,
          },
          AlertProperties: {
            HighlightRow: true,
          },
        },
      ],
    },
  },
};
```

## Add or Update

AdapTable provides a companion `addOrUpdateGridData` function.

This should be used when the rows received can be either new or existing.

If the primary key exists in a row, the function will call `updateGridData` (see [Updating Grid Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-update/index.md))

If the primary key doesn't exist in a row, the function will call `addGridData`.

### `addOrUpdateGridData`

Adds or Updates Rows in AG Grid (asynchronously if required)

Use this function to safely add or update data inside AG Grid while your application is live.

The function checks whether the Primary Key value exists and then:

- Sends all **existing** rows to `updateGridData`
- Sends all **new** rows to `addGridData`

```ts {7}
// Add a new Trade to the Grid
const newTrade: ITrade = getTradeFromServer();
// Set Price for Trade (of Id: 2) to 500
const existingTrade: ITrade =
  adaptableApi.gridApi.getRowNodeForPrimaryKey(2).data;
existingTrade.notional = 500;
adaptableApi.gridApi.addOrUpdateGridData([newTrade, existingTrade]);
```
