# Updating Rows in AG Grid

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

- AdapTable provides an `updateGridData` function to update rows in AG Grid
- This can be run synchronously or asynchronously

AdapTable facilitates updating rows in AG Grid, while the application is live.

This is done via the `updateGridData` 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 update rows in 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, and should be used to update entire **rows**.

To update a single **cell** use `setCellValue` (or `setCellValues` for multiple cells) - see [Updating Grid Cells](https://www.adaptabletools.com/docs/handbook-managing-grid-data-cells/index.md) for details

The `updateGridData` 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 `Update`, which will trigger [Cell / Row Flashing](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) and [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md)

AdapTable will not apply any [Validation Alerts](https://www.adaptabletools.com/docs/handbook-alerting-validation/index.md) when using the `updateGridData` function

### `updateGridData`

Updates Rows in AG Grid (asynchronously if required)

Use this function to safely update data inside AG Grid while your application is live (asynchronously if required).

The signature of the function is:

```ts
updateGridData(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 updated.

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

- `applyTransaction` with param of `update` - 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

```ts {5,12}
// Set Price for Trade (of Id: 2) to 500
const node: IRowNode = adaptableApi.gridApi.getRowNodeForPrimaryKey(2);
const trade: ITrade = node.data;
trade.notional = 500;
adaptableApi.gridApi.updateGridData([trade]);

// Set Price for Trade (of Id: 2) to 500 asynchronously
const node: IRowNode = adaptableApi.gridApi.getRowNodeForPrimaryKey(2);
const trade: ITrade = node.data;
trade.notional = 500;
const config: DataUpdateConfig = {runAsync: true};
adaptableApi.gridApi.updateGridData([trade], config);
```

**Example: Updating Row Data**

Updating Rows in AG Grid at run-time

- This demo shows how to update rows in AG Grid at run-time using the `updateGridData` 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 updateReact(): WebFramework {
  return {
    id: 10270250,
    name: 'react',
    full_name: 'facebook/react',
    html_url: 'https://github.com/facebook/react',
    description:
      'A declarative, efficient, and flexible JavaScript library for building user interfaces.',
    created_at: new Date('2013-05-24T16:15:54').toDateString(),
    updated_at: new Date(Date.now()).toDateString(),
    pushed_at: new Date('2021-12-19T14:34:59').toDateString(),
    homepage: 'https://reactjs.org',
    github_stars: 201548,
    language: 'JavaScript',
    forks_count: 36403,
    open_issues_count: 920,
    license: 'MIT License',
    topics: ['declarative', 'frontend', 'javascript', 'library', 'react', 'ui'],
    github_watchers: 6527,
    has_projects: true,
    has_wiki: true,
    has_pages: true,
    closed_issues_count: 10326,
    open_pr_count: 249,
    closed_pr_count: 11408,
    week_issue_change: 5,
  };
}

export function updateAngular(): WebFramework {
  return {
    id: 24195339,
    name: 'angular',
    full_name: 'angular/angular',
    html_url: 'https://github.com/angular/angular',
    description: 'The modern web developer’s platform',
    created_at: new Date('2014-09-18T16:12:01').toDateString(),
    updated_at: new Date(Date.now()).toDateString(),
    pushed_at: new Date('2021-12-19T21:54:01').toDateString(),
    homepage: 'https://angular.io',
    github_stars: 69651,
    language: 'TypeScript',
    forks_count: 20569,
    open_issues_count: 1889,
    license: 'MIT License',
    topics: [
      'angular',
      'javascript',
      'pwa',
      'typescript',
      'web',
      'web-framework',
      'web-performance',
    ],
    github_watchers: 5026,
    has_projects: true,
    has_wiki: false,
    has_pages: false,
    closed_issues_count: 21706,
    open_pr_count: 159,
    closed_pr_count: 20052,
    week_issue_change: 12,
  };
}

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Updating Grid Rows',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'ButtonToolbar',
        title: 'Buttons',
        toolbarButtons: [
          {
            label: 'Update React',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const react: WebFramework = updateReact();
              const dataUpdateConfig: DataUpdateConfig = {
                runAsync: true,
                addIndex: 0,
              };
              context.adaptableApi.gridApi.updateGridData(
                [react],
                dataUpdateConfig
              );
            },
            buttonStyle: {
              tone: 'info',
              variant: 'text',
            },
            disabled: () => false,
          },
          {
            label: 'Update Angular',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const angular: WebFramework = updateAngular();
              const dataUpdateConfig: DataUpdateConfig = {
                runAsync: true,
              };
              context.adaptableApi.gridApi.updateGridData(
                [angular],
                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',
            'github_watchers',
            'updated_at',
            'license',
            'created_at',
            'has_wiki',
            '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,
        },
      ],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'Flashing_Cell_Any_Change',
          Rule: 'ANY_CHANGE()',
          Scope: {
            All: true,
          },
        },
      ],
    },
  },
};
```

## Add or Update

AdapTable provides a companion `addOrUpdateGridData` function.

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

See [using the addOrUpdateGridData function](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-add/index.md#add-or-update) for more details
