# Loading Grid Data

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

- AdapTable provides a Grid API function which can be used to load and reload the Grid as required
- This fully supports delayed loading (i.e. fetching data after AG Grid has initialised)

The `loadGridData` function in [Grid API](https://www.adaptabletools.com/docs/technical-reference-managing-grid-data/index.md) is used to provide AG Grid with a full set of row data.

- We strongly recommend **using this function** to load or replace AG Grid data, rather than calling `setRowData` on the AG Grid API directly
- The function ultimately calls AG Grid but first performs AdapTable checks and publishes the [Row Changed Event](https://www.adaptabletools.com/docs/handbook-managing-grid-data-changed-events/index.md)

- This function should be used when you want to populate AG Grid **programmatically** at run-time
- This is very popular with **delayed data scenarios** - when the data is not available until after the Grid has loaded

AdapTable **replaces** all the current data in the Grid with the data provided in the function.

### `loadGridData`

Loads AG Grid with either initial or replacement set of data

Use this function to provide AG Grid with either an initial set of Data or to replace the Data at run-time.

The function receives an array of data rows and returns void:

```ts
loadGridData(data: any[]): void;
```

```ts {3}
// Provide initial set of Trades to the Grid
const trades: ITrade[] = getTradesFromServer();
adaptableApi.gridApi.loadGridData(trades);
```

This function triggers the [Row Changed Event](https://www.adaptabletools.com/docs/technical-reference-managing-grid-data/index.md) with a Trigger of `Load`.

**Example: Loading Grid Data**

Loading data in AG Grid and AdapTable at run-time

- This demo opens AG Grid and AdapTable with no data provided (a typical "Delayed Data" scenario)
- Initial data (_JavaScript_ rows) is added by clicking the `Load Initial Grid Data` button in the Dashboard
- A replacement set of data (_TypeScript_ rows) can be provided by clicking the `Re-load Grid Data` button in the Dashboard
- Note: You are still able to create AdapTable objects (e.g. Format Columns) in the absence of data

- Create a [Format Column](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) on a row (e.g. '[language]="JavaScript" ')
- Load the Data by clicking the button in the Dashboard
- Note that Format Column is applied to the loaded data

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts
  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,
  DashboardButtonContext,
} from '@adaptabletools/adaptable';
import {rowData} from './rowData';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Loading Grid Data',
  dashboardOptions: {
    customDashboardButtons: [
      {
        label: 'Load Initial Grid Data',
        onClick: (
          button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          const jsRows: WebFramework[] = rowData.filter(
            (f: WebFramework) => f.language === 'JavaScript'
          );
          context.adaptableApi.gridApi.loadGridData(jsRows);
        },
        buttonStyle: {
          variant: 'raised',
          tone: 'warning',
        },
        disabled: () => false,
      },
      {
        label: 'Re-load Grid Data',
        onClick: (
          button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          const tsRows: WebFramework[] = rowData.filter(
            (f: WebFramework) => f.language === 'TypeScript'
          );
          context.adaptableApi.gridApi.loadGridData(tsRows);
        },
        buttonStyle: {
          variant: 'outlined',
          tone: 'neutral',
        },
      },
    ],
  },
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: ['name', 'language', 'license'],
          Name: 'Standard Layout',
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {rowData} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,

    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  // set row data to null as we will get it later
  rowData: null,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

- Only use `loadGridData` to replace the whole data set if it is definitely required, or there is no alternative
- Because the entire data set is replaced, `loadGridData` will **not** invoke [Cell or Row Flashing](https://www.adaptabletools.com/docs/handbook-flashing-cell/index.md) nor trigger [Alerts](https://www.adaptabletools.com/docs/handbook-alerting/index.md)

See [Updating Grid Rows](https://www.adaptabletools.com/docs/handbook-managing-grid-data-rows-update/index.md) or [Updating Cells](https://www.adaptabletools.com/docs/handbook-managing-grid-data-cells/index.md) for better alternatives that update only specific cells or rows

## Delaying Grid Data

All the demos in this site load the data up front as part of initialising AG Grid.

This is because they are designed to illustrate run-time features of AdapTable.

However in many advanced, real-world, scenarios lazy loading is required.

AdapTable supports lazy-loading, for both Columns and row data.

**Example: Delaying Grid Data**

Adding extra columns after AG Grid has loaded

- In this demo at startup no Columns or Data is provided
- Clicking a button starts a process that adds **all** the columns and data dynamically after the grid loads and then creates and sets a Layout as follows:
  - after 1 second: add the new column definitions using `setAgGridColumnDefinitions` in Adaptable's [Grid API](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md)
  - after 2 seconds: load the data using `loadGridData` in Adaptable's [Grid API](https://www.adaptabletools.com/docs/handbook-managing-grid-data/index.md)
  - after 3 seconds: create and set the _Grouped Layout_ using `createAndSetLayout` in [Layout API](https://www.adaptabletools.com/docs/technical-reference-layouts/index.md)
- All these steps are accompanied by [System Status](https://www.adaptabletools.com/docs/ui-tutorial-using-toast-notifications/index.md) messages
### Expand to see the code

```ts
api.systemStatusApi.setWarningSystemStatus('Setting Up Columns');
// Add the Column Defs to the Columns 1 second after the Grid loads using setAgGridColumnDefinitions method in GridApi
setTimeout(() => {
  api.gridApi.setAgGridColumnDefinitions(columnDefs);
  api.systemStatusApi.setInfoSystemStatus('Loading Data');
}, 1000);
// Add data to grid after a further second using loadGridData method in GridApi
setTimeout(() => {
  api.systemStatusApi.setSuccessSystemStatus('Creating a "Grouped Layout"');
  api.gridApi.loadGridData(rowData);
}, 2000);
// After a further second create and set a new Layout
setTimeout(() => {
  const groupedLayout: Layout = {
    TableColumns: ['price', 'model', 'available', 'firstBought'],
    RowGroupedColumns: ['make'],
    Name: 'Grouped Layout',
    TableAggregationColumns: [
      {
        ColumnId: 'price',
        AggFunc: 'sum',
      },
    ],
  };
  api.layoutApi.createAndSetLayout(groupedLayout);
  api.systemStatusApi.setInfoSystemStatus(
    'All Data, Columns and Layouts Loaded'
  );
}, 3000);
```

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts
  rowData.ts
  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 {
  AdaptableApi,
  AdaptableButton,
  AdaptableOptions,
  DashboardButtonContext,
  Layout,
} from '@adaptabletools/adaptable';
import {columnDefs} from './columnDefs';
import {Car, rowData} from './rowData';

export const adaptableOptions: AdaptableOptions<Car> = {
  primaryKey: 'model',
  adaptableId: 'Dynamic Columns',
  dashboardOptions: {
    customDashboardButtons: [
      {
        label: 'Add Dynamic Columns & Data',
        onClick: (
          button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          const api: AdaptableApi = context.adaptableApi;

          api.systemStatusApi.setWarningSystemStatus('Setting Up Columns');
          // Add the Column Defs to the Columns 1 second after the Grid loads using setAgGridColumnDefinitions method in GridApi
          setTimeout(() => {
            api.gridApi.setAgGridColumnDefinitions(columnDefs);
            api.systemStatusApi.setInfoSystemStatus('Loading Data');
          }, 1000);

          // Add data to grid after a further second using loadGridData method in GridApi
          setTimeout(() => {
            api.systemStatusApi.setSuccessSystemStatus(
              'Creating a "Grouped Layout"'
            );
            api.gridApi.loadGridData(rowData);
          }, 2000);

          // After a further second create and set a new Layout
          setTimeout(() => {
            const groupedLayout: Layout = {
              TableColumns: ['price', 'model', 'available', 'firstBought'],
              RowGroupedColumns: ['make'],
              Name: 'Grouped Layout',
              TableAggregationColumns: [
                {
                  ColumnId: 'price',
                  AggFunc: 'sum',
                },
              ],
            };
            api.layoutApi.createAndSetLayout(groupedLayout);
            api.systemStatusApi.setInfoSystemStatus(
              'All Data, Columns and Layouts Loaded'
            );
          }, 3000);
        },
        buttonStyle: {
          variant: 'raised',
          tone: 'warning',
        },
        disabled: () => false,
      },
    ],
  },
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Dashboard: {
      Tabs: [
        {
          Name: 'Messages',
          Toolbars: ['SystemStatus', 'Layout'],
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {Car} from './rowData';

export const gridOptions: GridOptions<Car> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,

    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  // set columnDefs to empty array as we will get it later
  columnDefs: [],
  // set row data to null as we will get it later
  rowData: null,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  adaptableApi.systemStatusApi.setErrorSystemStatus('Nothing has been Loaded');
};
```

**`src/rowData.ts`**

```ts
export interface Car {
  make: string;
  model: string;
  price: number;
  firstUsed: Date;
  firstBought: Date;
  available: boolean;
  milesToGallon: number;
  EnergyRating: number;
  EfficencyRating: number;
}

export const rowData: Car[] = [
  {
    make: 'Toyota',
    model: 'Celica',
    price: 35000,
    firstUsed: new Date(2017, 11, 4),
    firstBought: new Date(2017, 11, 4),
    available: true,
    milesToGallon: 21.345676,
    EnergyRating: 1,
    EfficencyRating: 2,
  },
  {
    make: 'Toyota',
    model: 'Yaris',
    price: 40000,
    firstUsed: new Date(2013, 1, 15),
    firstBought: new Date(2013, 1, 15),
    available: true,
    milesToGallon: 29.32432423,
    EnergyRating: 4,
    EfficencyRating: 1,
  },
  {
    make: 'Toyota',
    model: 'Corolla',
    price: 28000,
    firstUsed: new Date(2017, 6, 9),
    firstBought: new Date(2017, 6, 9),
    available: false,
    milesToGallon: 32.9032523473287,
    EnergyRating: 5,
    EfficencyRating: 2,
  },
  {
    make: 'Ford',
    model: 'Mondeo',
    price: 32000,
    firstUsed: new Date(2009, 10, 2),
    firstBought: new Date(2009, 10, 2),
    available: true,
    milesToGallon: 28.247893473289,
    EnergyRating: 4,
    EfficencyRating: 2,
  },
  {
    make: 'Ford',
    model: 'Fiesta',
    price: 35000,
    firstUsed: new Date(2018, 8, 12),
    firstBought: new Date(2018, 8, 12),
    available: false,
    milesToGallon: 34.0001,
    EnergyRating: 5,
    EfficencyRating: 3,
  },
  {
    make: 'Ford',
    model: 'Focus',
    price: 26750,
    firstUsed: new Date(2017, 3, 3),
    firstBought: new Date(2017, 3, 3),
    available: false,
    milesToGallon: 31.2432432423,
    EnergyRating: 3,
    EfficencyRating: 1,
  },
  {
    make: 'Ford',
    model: 'Galaxy',
    price: 41000,
    firstUsed: new Date(2015, 4, 14),
    firstBought: new Date(2015, 4, 14),
    available: false,
    milesToGallon: 29.29432404,
    EnergyRating: 2,
    EfficencyRating: 5,
  },
  {
    make: 'Porsche',
    model: 'Boxter',
    price: 72500,
    firstUsed: new Date(2016, 1, 28),
    firstBought: new Date(2016, 1, 28),
    available: true,
    milesToGallon: 32.29580292,
    EnergyRating: 4,
    EfficencyRating: 4,
  },
  {
    make: 'Porsche',
    model: 'Mission',
    price: 81000,
    firstUsed: new Date(2008, 10, 7),
    firstBought: new Date(2008, 10, 7),
    available: false,
    milesToGallon: 35.7822957,
    EnergyRating: 5,
    EfficencyRating: 2,
  },
  {
    make: 'Mitsubbishi',
    model: 'Outlander',
    price: 97800,
    firstUsed: new Date(2017, 11, 14),
    firstBought: new Date(2017, 11, 14),
    available: true,
    milesToGallon: 19.224309,
    EnergyRating: 4,
    EfficencyRating: 5,
  },
];
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';
import {Car} from './rowData';

export const columnDefs: ColDef<Car>[] = [
  {
    headerName: 'Make',
    field: 'make',
    filter: true,
    editable: false,
    enableRowGroup: true,
    enablePivot: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Model',
    field: 'model',
    filter: true,
    editable: false,
    cellDataType: 'text',
  },
  {
    headerName: 'Price',
    field: 'price',
    filter: true,
    editable: false,
    cellDataType: 'number',
  },
  {
    headerName: 'Miles To Gallon',
    field: 'milesToGallon',
    filter: true,
    editable: false,
    cellDataType: 'number',
  },
  {
    headerName: 'First Used',
    field: 'firstUsed',
    filter: true,
    editable: false,
    cellDataType: 'date',
  },
  {
    headerName: 'First Bought',
    field: 'firstBought',
    filter: true,
    editable: false,
    cellDataType: 'date',
  },
  {
    headerName: 'Available',
    field: 'available',
    filter: true,
    editable: true,
    cellDataType: 'boolean',
  },
];
```
