# Custom AdapTable State

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

- Bespoke data can be stored in AdapTable State by using the Application section

AdapTable provides the Application section of [Initial Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md) for storing custom state.

To persist custom data *outside* of Adaptable State (e.g. in an envelope wrapping it), do so in [persistState](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md#persiststate) and unwrap it again in `loadState`

Application contains a simple set of key / value pairs designed for storing bespoke data.

A common use case is to store grid-related options which the User changed (e.g. Filter Bar visibility).

AdapTable takes care of the full persistence / retrieval of these objects as part of [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md)

**Example: Custom Data in Adaptable State**

Using Application Initial State to save bespoke user data

 

- This example shows how you can use Application section of Adaptable State to store custom data, persisted between sessions via custom `loadState` / `persistState`
- Persistence uses a mock remote service here; in production call your own API from the same functions (e.g. Supabase, Firebase, S3, etc.)
- 2 properties are kept in Application State:
  - the time when the button was clicked
  - whether Filter bar is displayed
- When the demo first loads the Grid shows with the Filter Bar hidden (as visibility was set to false in Filter Options) and with the Button showing loaded time
- Each time Filter Bar Visibility is changed - either through Toolbar or via the Column Menu - an entry in Application State is updated
- Likewise each time the Button is clicked the Application State is updated and the Button displays the time it was updated
- Refreshing the grid will display the Grid with Filter bar as it was last set and the button showing the last time it was clicked

```ts
  stateOptions: {
    loadState: (config: AdaptableStateFunctionConfig) => {
      return remotePersistenceService.loadAdaptableState(config.adaptableStateKey);
    },
            
    persistState: (
      state: AdaptablePersistentState,
      config: AdaptableStateFunctionConfig
    ) => {
      // If using Supabase it would be something like:
      //   supabase.from('adaptable_state').upsert({ state_key, state_value })
      return remotePersistenceService.persistAdaptableState(
        state,
        config.adaptableStateKey,
        config.userName
      );
    }
  }
```

- Refresh the page and note that the Filter Bar visibility is the same value to which it was last set and the Button time is not updated
- Reset the persisted state and note that now the Filter Bar is hidden (as value from Filter Options is used) and the Button click count is reset

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]
  MockRemotePersistenceService.ts
  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 {
  AdaptableApi,
  AdaptableButton,
  AdaptableOptions,
  AdaptablePersistentState,
  AdaptableStateFunctionConfig,
  ApplicationDataEntry,
  CustomToolbarButtonContext,
  DashboardButtonContext,
} from '@adaptabletools/adaptable';
import {MockRemotePersistenceService} from './MockRemotePersistenceService';

import {WebFramework} from './rowData';

const remotePersistenceService = new MockRemotePersistenceService();

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Application State Demo',
  adaptableStateKey: 'docs/ApplicationStateDemo',
  filterOptions: {
    columnFilterOptions: {
      showQuickFilter: false,
    },
  },
  dashboardOptions: {
    customDashboardButtons: [
      {
        label: 'Reset State',
        buttonStyle: {
          tone: 'neutral',
          variant: 'outlined',
        },
        onClick: (
          _button: AdaptableButton<DashboardButtonContext>,
          context: DashboardButtonContext
        ) => {
          remotePersistenceService.clearAdaptableState(
            context.adaptableApi.optionsApi.getAdaptableStateKey(),
            context.userName
          );
          context.adaptableApi.applicationApi.editApplicationDataEntry({
            Key: 'TimesClicked',
            Value: 0,
          });
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
    customToolbars: [
      {
        name: 'TimesClickedButton',
        toolbarButtons: [
          {
            label: 'Click Me',
            buttonStyle: {
              tone: 'neutral',
              variant: 'outlined',
            },
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              let entry: ApplicationDataEntry | undefined =
                context.adaptableApi.applicationApi.getApplicationDataEntryByKey(
                  'TimesClicked'
                );
              if (entry) {
                entry.Value = entry.Value + 1;
                context.adaptableApi.applicationApi.editApplicationDataEntry(
                  entry
                );

                context.adaptableApi.systemStatusApi.setWarningSystemStatus(
                  'Times Clicked: ' + entry.Value
                );
              }
            },
          },
        ],
      },
    ],
  },
  stateOptions: {
    loadState: (config: AdaptableStateFunctionConfig) => {
      return remotePersistenceService.loadAdaptableState(
        config.adaptableStateKey
      );
    },
    persistState: (
      state: AdaptablePersistentState,
      config: AdaptableStateFunctionConfig
    ) => {
      return remotePersistenceService.persistAdaptableState(
        state,
        config.adaptableStateKey,
        config.userName
      );
    },
  },

  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['ColumnFilter', 'TimesClickedButton', '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,
  ApplicationDataEntry,
} from '@adaptabletools/adaptable';

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  const timesClickedEntryKey: string = 'TimesClicked';
  let timesClickedEntry: ApplicationDataEntry | undefined =
    adaptableApi.applicationApi.getApplicationDataEntryByKey(
      timesClickedEntryKey
    );
  if (!timesClickedEntry) {
    timesClickedEntry = {
      Key: timesClickedEntryKey,
      Value: 0,
    };
    adaptableApi.applicationApi.addApplicationDataEntry(timesClickedEntry);
  }
  if (timesClickedEntry.Value > 0) {
    adaptableApi.systemStatusApi.setSuccessSystemStatus(
      'Times Clicked: ' + timesClickedEntry.Value
    );
  } else {
    adaptableApi.systemStatusApi.setInfoSystemStatus(
      'Times Clicked: ' + timesClickedEntry.Value
    );
  }

  let filterVisibilityEntry: ApplicationDataEntry | undefined =
    adaptableApi.applicationApi.getApplicationDataEntryByKey(
      'QuickFilterVisibility'
    );

  if (filterVisibilityEntry) {
    filterVisibilityEntry.Value == true
      ? adaptableApi.filterApi.columnFilterApi.showQuickFilterBar()
      : adaptableApi.filterApi.columnFilterApi.hideQuickFilterBar();
  }
  adaptableApi.eventApi.on('AdaptableStateChanged', stateChangedInfo => {
    if (stateChangedInfo.actionName == 'SYSTEM_QUICK_FILTER_BAR_SHOW') {
      filterVisibilityEntry = {
        Key: 'QuickFilterVisibility',
        Value: true,
      };
      adaptableApi.applicationApi.editApplicationDataEntry(
        filterVisibilityEntry
      );
    }
    if (stateChangedInfo.actionName == 'SYSTEM_QUICK_FILTER_BAR_HIDE') {
      filterVisibilityEntry = {
        Key: 'QuickFilterVisibility',
        Value: false,
      };
      adaptableApi.applicationApi.editApplicationDataEntry(
        filterVisibilityEntry
      );
    }
  });
};
```
**`src/MockRemotePersistenceService.ts`**

```ts
/**
 * Simulates a remote persistence layer for docs demos.
 *
 * In production you would replace these methods with calls to your API
 * (e.g. Supabase, Firebase, S3, a custom backend, etc.).
 *
 * Here we store JSON under a dedicated localStorage namespace and add a
 * short delay so load/persist remain clearly asynchronous.
 */
export class MockRemotePersistenceService {
  private readonly storagePrefix = 'adaptable-docs-remote-state:';
  private readonly networkDelayMs = 150;
  private readonly debugMode: boolean;

  constructor(config?: {debugMode?: boolean}) {
    this.debugMode = !!config?.debugMode;
  }

  async loadAdaptableState(stateKey: string): Promise<any> {
    await this.simulateNetwork();
    const stateTextValue = localStorage.getItem(this.toStorageKey(stateKey));
    const state = JSON.parse(stateTextValue ?? '{}');
    this.log(`LOAD_STATE::${stateKey}`, state);
    return state;
  }

  async persistAdaptableState(
    state: any,
    stateKey: string,
    userName: string
  ): Promise<void> {
    await this.simulateNetwork();
    localStorage.setItem(this.toStorageKey(stateKey), JSON.stringify(state));
    this.log(`PERSIST_STATE::${stateKey}`, {userName, state});
  }

  async clearAdaptableState(stateKey: string, userName: string): Promise<void> {
    await this.simulateNetwork();
    localStorage.removeItem(this.toStorageKey(stateKey));
    this.log(`CLEAR_STATE::${stateKey}`, {userName});
  }

  private toStorageKey(stateKey: string): string {
    return `${this.storagePrefix}${stateKey}`;
  }

  private simulateNetwork(): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, this.networkDelayMs));
  }

  private log(...params: any) {
    if (!this.debugMode) {
      return;
    }
    console.log(...params);
  }
}
```

Application State and the Application API are in the [AdapTable State Technical Reference](https://www.adaptabletools.com/docs/technical-reference-adaptable-state/index.md)
