# Listening to AdapTable State

Canonical page: https://www.adaptabletools.com/docs/dev-guide-adaptable-state-events

- The AdapTable State Changed Event fires whenever anything changes in Adaptable State
- The Before Adaptable State Change Event fires immediately before that update
- The AdapTable State Reloaded Event fires when State reloads

AdapTable provides a stream of every change to AdapTable State.

That covers Redux-backed updates after the Grid is ready — Layouts, searches, styles, Module objects and similar — not mouse clicks, and not AG Grid data edits.

The Event's messages can easily be streamed to 3rd party monitoring applications for use by Support Teams

There is also an Adaptable State Reloaded Event which fires when the State is reloaded

## AdapTable State Changed Event

The Adaptable State Changed Event is fired every time that any [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md) changes.

The [Event's Info](https://www.adaptabletools.com/docs/technical-reference-adaptable-state/index.md) provides very extensive information about the State Change in question including:

- what action triggered the change
- who was the user
- when it happened
- which AdapTable instance
- before and after copies of Adaptable State

**Example: Adaptable State Changes**

Monitoring changes in AdapTable State

- In this example we listen to the Adaptable State Changed Event and output each Message:
  - In full to the console
  - As a [System Status Message](https://www.adaptabletools.com/docs/ui-tutorial-using-toast-notifications/index.md) with the Action Name as the `Header` and the full message as the `Description`

- Perform some typical activity in the Grid and open System Status screen to see the full details of all the messages sent

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
  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 {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Adaptable State Changed',
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Default',
          Toolbars: ['SystemStatus'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['SystemStatus'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'language',
            'github_watchers',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  adaptableApi.eventApi.on(
    'AdaptableStateChanged',
    (stateChangedInfo: AdaptableStateChangedInfo) => {
      // ignore system status events
      // calling `setInfoSystemStatus` triggers another event
      if (!stateChangedInfo.action.type.includes('SYSTEM_STATUS')) {
        let info = '';
        try {
          // it fails for objects with complex references
          info = JSON.stringify(stateChangedInfo.action);
        } catch (e) {
          info = 'Could not stringify action';
        }

        const message = 'Action Name: ' + stateChangedInfo.actionName;
        adaptableApi.systemStatusApi.setInfoSystemStatus(message, info);

        console.info('Audit Message', {
          actionName: stateChangedInfo.actionName,
          // logging string version
          // the SandPack gets slow when logging complex objects
          info,
        });
      }
    }
  );
};
```

### Filtering State Changed Messages

The Event's Args can be filtered so only particular actions are logged.

This allows Support Teams to listen only to the grid changes that they are interested in

**Example: Filtering Adaptable State Changed Messages**

Filtering messages fired by the Adaptable State Changed Event

- In this example we filter the Adaptable State Changed Event only to log messages relating to Quick Search, Column Filters and the Grid Filter.
- We send the messages provided by the Event:
  - In full to the console
  - As a [System Status Message](https://www.adaptabletools.com/docs/ui-tutorial-using-toast-notifications/index.md) with the Action Name as the `Header` and the full message as the `Description`

- Run some quick searches and see the Event messages that are sent
- Perform other Grid actions and note that nothing is sent processed by the Event

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
  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 {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Filtering Adaptable State Changed',
  initialState: {
    Dashboard: {
      PinnedToolbars: ['SystemStatus', 'GridFilter'],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['SystemStatus', 'QuickSearch'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'language',
            'github_watchers',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  adaptableApi.eventApi.on(
    'AdaptableStateChanged',
    (stateChangedInfo: AdaptableStateChangedInfo) => {
      // ignore system status events
      // calling `setInfoSystemStatus` triggers another event
      if (
        stateChangedInfo.action.type.includes('QUICK_SEARCH') ||
        stateChangedInfo.action.type.includes('GRID_FILTER') ||
        stateChangedInfo.action.type.includes('COLUMN_FILTER')
      ) {
        let info: any = stateChangedInfo.action;
        try {
          // it fails for objects with complex references
          info = JSON.stringify(stateChangedInfo.action);
        } catch (e) {
          info = 'Could not stringify action';
        }

        const message = 'Action Name: ' + stateChangedInfo.actionName;
        adaptableApi.systemStatusApi.setInfoSystemStatus(
          message,
          'text: ' + info
        );

        console.info('Audit Message', {
          actionName: stateChangedInfo.actionName,
          // logging string version
          // the SandPack gets slow when logging complex objects
          info,
        });
      }
    }
  );
};
```

### Actions

Each State Change is triggered by a [Redux Action](https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers) (the technical solution Adaptable uses to manage state)

Each Action contains useful objects pertaining to that particular change.

#### Action Names

To help Support Teams, the `actionName` property in the Action is also provided as a full level property.

It describes exactly what the Action does, and can be used to listen to a particular State Change.

For instance to react to values being changed in a [FreeText Column](https://www.adaptabletools.com/docs/handbook-freetext-column/index.md) you would do:

```ts
api.eventApi.on(
  'AdaptableStateChanged',
  (statechangedInfo: AdaptableStateChangedInfo) => {
    if (
      statechangedInfo.actionName == 'FREE_TEXT_COLUMN_ADD_EDIT_STORED_VALUE'
    ) {
      // do something with the change
    }
  }
);
```

### Full Action Name List

This is the full list of all `actionName` properties, together with what the Action does:

@import file="reduxactions/reduxactions.page.md" section="Redux Actions"

## Other State Events

AdapTable provides 2 other Events that handle changes in AdapTable State:

### Before AdapTable State Change

The `BeforeAdaptableStateChange` Event fires **before** a change is made in AdapTable State.

- This is very useful if you wish to show a progress indicator for an action which takes several seconds
- Or if there are other actions which you wish to perform while the State changes

The `EventInfo` contains the current State and the Redux Action which is about to be performed.

- It is not possible to cancel the Redux Action with this Event
- Do **not** use this event to mutate the Adaptable state (e.g. to dispatch another action)

### AdapTable State Reloaded

The `AdaptableStateReloaded` Event fires whenever the AdapTable State reloads.

The `EventInfo` contains the new and old state allowing users easily to diff the changes.
