# Managing Rows in AG Grid

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

- AdapTable provides a useful `manageGridData` function
- This enables adding, updating and deleting AG Grid Rows in one transaction
- This function can be run synchronously or asynchronously

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

This is done via the `manageGridData` 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 manage rows in AG Grid, rather than the AG Grid API directly
- AdapTable compares each updated row with the row it replaces, including rows that are not currently rendered, and reports every cell that changed
- When rows are updated with the AG Grid API directly, AdapTable sees changes only to the rows that are rendered at that moment

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

AdapTable also provides standalone functions if you wish **only** to add, update or delete Grid Rows, see:
- [Adding Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-add/index.md)
- [Updating Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-update/index.md)
- [Deleting Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-delete/index.md)

The `manageGridData` function does 3 things:

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

- compares each updated row with the row it replaces and fires a [Cell Changed Event](https://www.adaptabletools.com/docs/handbook-managing-grid-data-changed-events/index.md#cell-changed-event) for every cell whose value changed (which drives [Cell / Row Flashing](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) and [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md) for updated rows)

- publishes the [Row Changed Event](https://www.adaptabletools.com/docs/handbook-managing-grid-data-changed-events/index.md#row-changed-event) with the relevant Trigger (which will in turn trigger any [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md) for added and deleted rows)

Pass a **new object** for each row in `updateRows`, never the row's current data changed in place: AdapTable cannot see changes made to the current object itself (see [Updating Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-update/index.md))

### `manageGridData`

Manages (ie. adds, updates or deletes) AG Grid Rows (asynchronously if required)

Use this function to add, update or delete rows in AG Grid while your application is live (asynchronously if required).

The signature of the function is:

```ts
manageGridData(dataRowConfig: DataRowConfig, dataUpdateConfig?: DataUpdateConfig): Promise<{
    addedRows: IRowNode[];
    updatedRows: IRowNode[];
    removedRows: IRowNode[];
  }>;
```

As can be seen, it receives 2 arguments:

- a [`DataRowConfig`](https://www.adaptabletools.com/docs/reference/datarowconfig.md) object
- 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, updated and removed.

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

- `applyTransaction` with the appropriate param - 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>DataRowConfig</b>

The [`DataRowConfig`](https://www.adaptabletools.com/docs/reference/datarowconfig.md) object is used to provide the rows which need to be added, updated or deleted:

| Property | Type | Description |
| --- | --- | --- |
| [addRows](https://www.adaptabletools.com/docs/reference/datarowconfig.md#addrows) | `any[]` | Rows to add |
| [deleteRows](https://www.adaptabletools.com/docs/reference/datarowconfig.md#deleterows) | `any[]` | Rows to delete |
| [updateRows](https://www.adaptabletools.com/docs/reference/datarowconfig.md#updaterows) | `any[]` | Rows to update |

<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 {22}
// Create 2 new Rows to add to the Grid
const python: WebFramework = createPython();
const go: WebFramework = createGo();
// Update 2 existing rows in the Grid
const react: WebFramework = updateReact();
const angular: WebFramework = updateAngular();
// Retrieve 2 rows which should be deleted
const vueNode = adaptableApi.gridApi.getRowNodeForPrimaryKey(11730342);
const svelteNode = adaptableApi.gridApi.getRowNodeForPrimaryKey(74293321);
// Create Config Object with all 6 rows (2 add, 2 update and 2 delete)
const dataRowConfig: DataRowConfig = {
    addRows: [python, go],
    updateRows: [react, angular],
    deleteRows: [vueNode, svelteNode],
};
// Create a DataUpdate Config object to enable running asynchronously
const dataUpdateConfig: DataUpdateConfig = {
  runAsync: true,
  addIndex: 0,
};
// Call the manageGridData function to make all changes in one transaction
adaptableApi.gridApi.manageGridData(dataRowConfig, dataUpdateConfig);
```

**Example: Managing Row Data**

Managing AG Grid Rows at run-time

- This demo shows how to manage rows in AG Grid at run-time using the `manageGridData` function in Grid API
- Clicking the 'Manage Rows' will create a single transaction that simultaneously:
  - adds 2 Rows (Python and Go)
  - updates 2 Rows (React and Angular)
  - deletes 2 Rows (Vue and Svelte)

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,
  DataRowConfig,
  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 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: 'Adding Grid Rows',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'ButtonToolbar',
        title: 'Buttons',
        toolbarButtons: [
          {
            label: 'Manage Rows',
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              
              const gridApi = context.adaptableApi.gridApi;
              const python: WebFramework = createPython();
              const go: WebFramework = createGo();
              const react: WebFramework = updateReact();
              const angular: WebFramework = updateAngular();
              const vueNode = gridApi.getRowNodeForPrimaryKey(11730342);
              const svelteNode = gridApi.getRowNodeForPrimaryKey(74293321);
              const dataRowConfig: DataRowConfig = {
                  addRows: [python, go],
                  updateRows: [react, angular],
                  deleteRows: [vueNode, svelteNode],
              };
              const dataUpdateConfig: DataUpdateConfig = {
                runAsync: true,
                addIndex: 0,
              };
              gridApi.manageGridData(dataRowConfig, dataUpdateConfig);
            },
            buttonStyle: {
              tone: 'info',
              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,
          },
        },
      ],
    },
    FlashingCell: {
      FlashingCellDefinitions: [
        {
          Name: 'Flashing_Cell_Any_Change',
          Rule: 'ANY_CHANGE()',
          Scope: {
            All: true,
          },
        },
      ],
    },
  },
};
```
