# AdapTable State Persistence Guide

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

- By default, AdapTable State is saved to local storage — you don't need to do anything
- The storage key is `adaptableStateKey` (it defaults to `adaptableId` if you omit it)
- Most production apps use remote storage via `loadState` and `persistState` in State Options

AdapTable State is designed to be persisted allowing for a seamless user experience between sessions.

## Local Storage

By default, AdapTable State is stored in the browser's local storage.

You don't need to implement any State Options functions for this. AdapTable reads and writes using `adaptableStateKey` in [Adaptable Options](https://www.adaptabletools.com/docs/technical-reference-adaptable-options/index.md).

If you omit `adaptableStateKey`, AdapTable uses the value of `adaptableId`

If using Local Storage, all user state will be lost each time the user clears the browser cache or switches computers

In practice, very few production users of AdapTable use local storage as their storage mechanism.

Learn more about setting the [adaptableStateKey](https://www.adaptabletools.com/docs/getting-started-adaptable-state-key/index.md) property in the Integration Guide

## Remote Storage

AdapTable also enables User State to be persisted remotely in - and subsequently retrieved from - any location of the users' choice.

- Most of the demos in this site use Local Storage for convenience sake
- However, the overwhelming majority of real world applications that use AdapTable leverage remote storage

Remote storage is accessible via a set of JavaScript functions available in [`State Options`](https://www.adaptabletools.com/docs/reference/stateoptions.md).

State Options provides 5 functions which allow developers to control the management of AdapTable State and supports custom implementations and functionality for managing state:

- This allows you to provide your own hydration or rehydration functionality if required
- It also allows you to enrich the State when it is being loaded with your own items (e.g. Application data or other custom properties)

| Function       | Enables                                              | Default AdapTable Behaviour     |
| -------------- | ---------------------------------------------------- | ------------------------------- |
| `loadState`    | Customization of State loading                       | Loads State from local storage  |
| `applyState`   | Hooking into State hydration                         | Returns the loaded State as-is  |
| `saveState`    | Customization of State that is about to be persisted | Returns the State as-is         |
| `persistState` | Customisation of State persistence                   | Persists State to local storage |
| `clearState`   | Clears persisted State on `reloadInitialState`       | Clears State from local storage |

Provide `loadState` and `persistState` **together**. If you supply only one, AdapTable still uses the localStorage fallback for the missing side, so remote and local copies can diverge (a warning is logged at startup).

AdapTable validates the State Option functions at startup and each time they are called, and logs an actionable error for the common mistakes:

- `saveState` / `applyState` declared `async` (or returning a Promise) - these functions are synchronous; the state is **not** persisted / applied
- `saveState` / `applyState` returning nothing - the state object passed in is used instead (so in-place mutations are kept), but add `return state;`
- `loadState` / `persistState` / `clearState` returning a plain value instead of a Promise - the value is used as if resolved

#### Remote Storage Workflow

The AdapTable State flow is as follows:

1. User Loads Page --> `loadState()` state1 -> `applyState(state1)`
2. state2 ---- ADAPTABLE NOW READY WITH STATE (state2)
3. User Updates State ------ `saveState(state3)`:
4. state4 -> `persistState(state4)`

<Illustration alt="AdaptableState Sequence Diagram" src="/images/docs/adaptable-state.png" />

All 4 functions work with [`AdaptablePersistentState`](https://www.adaptabletools.com/docs/reference/adaptablepersistentstate.md) - the persisted subset of Adaptable State.

`Internal`, `Popup`, `Comment` and `Plugins` are transient and are never passed to `saveState` / `persistState`, nor expected back from `loadState` / `applyState`

To store Adaptable State in a custom format (e.g. wrapped in an envelope with a version number, compressed or encrypted) do the wrapping in `persistState` and the unwrapping in `loadState` - these 2 functions own the storage format.

`saveState` and `applyState` must always receive and return Adaptable State: the result of `loadState` is merged with `initialState` section by section **before** `applyState` is called, so any wrapper object would be treated as (unknown) state sections.

### Load State

### `loadState`

Manages loading remote Adaptable State (async)

  [`AdaptableLoadStateFunction`](https://www.adaptabletools.com/docs/reference/adaptableloadstatefunction.md)

By default, AdapTable will read and return the state that was persisted from localStorage using `adaptableStateKey` (which defaults to `adaptableId` if you omit it)

`loadState` is nearly always used in conjunction with [persistState](#persiststate) - the other side of the persistence mechanism

The function is of type [`AdaptableLoadStateFunction`](https://www.adaptabletools.com/docs/reference/adaptableloadstatefunction.md):

```ts
export interface AdaptableLoadStateFunction {
  (adaptableStateFunctionConfig: AdaptableStateFunctionConfig): Promise<Partial<AdaptablePersistentState> | null | void>;
}
```

The returned state may be partial (only the sections that were persisted) or empty / `null` (nothing was persisted yet) - it is merged with `initialState` before being applied.

The function receives a [`AdaptableStateFunctionConfig`](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md) object defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [actionName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#actionname) | `string` | Name of the action that triggered the state change. |
| [adaptableApi](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableapi) | [`AdaptableApi`](https://www.adaptabletools.com/docs/reference/adaptableapi.md) | Adaptable API |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |
| [adaptableId](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableid) | `string` | Id of current Adaptable instance |
| [adaptableStateKey](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablestatekey) | `string` | State Key being used |
| [previousState](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#previousstate) | [`AdaptablePersistentState`](https://www.adaptabletools.com/docs/reference/adaptablepersistentstate.md) | Previous (persistent) state before the action was applied.<br/>This is useful for comparing changes or reverting if necessary. |
| [userName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#username) | `string` | current Adaptable user |

`loadState` can be used to load Adaptable State from the browser window object or a remote location

The hydration flow is: `loadState` -> merge with `initialState` -> `applyState`

The result of `loadState` is merged with `initialState` section by section, and the merged state is passed to [applyState](#applystate).

```ts
stateOptions: {
  // loadState is used to load the Adaptable State from a remote source (firebase in this example)
  // It returns a promise which is resolved when the State is retrieved from firebase
  loadState: () => {
    return firebase
      .database()
      .ref(`initialState/${id}`)
      .once('value')
      .then(function (snapshot) {
        const str = snapshot.val();
        return str ? JSON.parse(str) : {};
      });
  },
}
```

This function should be **asynchronous**

### Apply State

### `applyState`

Allows hooking into Adaptable State hydration

This function determines what state is (re)applied in AdapTable when AdapTable is initialized.

The function is of type `AdaptableApplyStateFunction`:

```ts
export interface AdaptableApplyStateFunction {
  (
    state: Partial<AdaptablePersistentState>, adaptableStateFunctionConfig: AdaptableStateFunctionConfig
  ): Partial<AdaptablePersistentState>;
}
```

This function is useful when the loaded Adaptable State needs to be adjusted before it is applied - e.g. to add defaults to all Layouts, or to [migrate](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-migrating-state/index.md) it manually.

The hydration flow is: `loadState` -> merge with `initialState` -> `applyState`

So the result of [loadState](#loadstate), merged with `initialState`, is passed to this function.

The state is `Partial` because only the sections present in either the persisted state or `initialState` are available at this point; missing sections are initialised with their defaults afterwards.

This function must be **synchronous** and **return** the state - an `async` function (or a Promise result) is reported as an error and the state is not applied; a missing `return` is reported and the state object passed in is used instead

The default implementation is to do nothing:

```ts
(state) => state
```

```ts
adaptableOptions = {
  stateOptions: {
    applyState: (state) => {
      // apply a default sort to all Layouts which don't define one
      state.Layout?.Layouts?.forEach(layout => {
        if (!layout.ColumnSorts?.length) {
          layout.ColumnSorts = [{ColumnId: 'github_stars', SortOrder: 'Desc'}];
        }
      });
      return state;
    },
  },
};
```

### Save State

### `saveState`

Allows customization of the Adaptable State about to be persisted

  [`AdaptableSaveStateFunction`](https://www.adaptabletools.com/docs/reference/adaptablesavestatefunction.md)

This function allows developers to customise the AdapTable State that is going to be persisted.

The function is of type [`AdaptableSaveStateFunction`](https://www.adaptabletools.com/docs/reference/adaptablesavestatefunction.md):

```ts
export interface AdaptableSaveStateFunction {
  (
    state: AdaptablePersistentState, adaptableStateFunctionConfig: AdaptableStateFunctionConfig
  ): AdaptablePersistentState;
}
```

The function receives a [`AdaptableStateFunctionConfig`](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md) object defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [actionName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#actionname) | `string` | Name of the action that triggered the state change. |
| [adaptableApi](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableapi) | [`AdaptableApi`](https://www.adaptabletools.com/docs/reference/adaptableapi.md) | Adaptable API |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |
| [adaptableId](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableid) | `string` | Id of current Adaptable instance |
| [adaptableStateKey](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablestatekey) | `string` | State Key being used |
| [previousState](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#previousstate) | [`AdaptablePersistentState`](https://www.adaptabletools.com/docs/reference/adaptablepersistentstate.md) | Previous (persistent) state before the action was applied.<br/>This is useful for comparing changes or reverting if necessary. |
| [userName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#username) | `string` | current Adaptable user |

The received state is the full persistent state of the Adaptable instance (the transient sections are already stripped); the function **must return** the state to persist.

If you also want to modify the persistence behaviour, you should implement the [persistState](#persiststate) as well

The persistence (dehydration) flow is the following: `saveState` -> `persistState`

This function must be **synchronous** and **return** the state - an `async` function (or a Promise result) is reported as an error and the state is not persisted; a missing `return` is reported and the state object passed in is persisted instead

The default implementation is to do nothing:

```ts
(state) => state
```

Use this function to remove or adjust parts of Adaptable State before persistence - e.g. to leave out a Layout which is always (re)created at startup
```ts
adaptableOptions = {
  stateOptions: {
    saveState: (state) => {
      state.Layout.Layouts = state.Layout.Layouts.filter(
        layout => layout.Metadata?.DEFAULT_PROP !== true
      ) as [Layout, ...Layout[]];
      return state;
    },
  },
};
```

To persist custom application data together with Adaptable State, use the [Application State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-custom/index.md) section; to persist Adaptable State in a custom format (envelope, compression etc.) use [persistState](#persiststate) and [loadState](#loadstate).

### Persist State

### `persistState`

Enables the customization of State persistence

  [`AdaptablePersistStateFunction`](https://www.adaptabletools.com/docs/reference/adaptablepersiststatefunction.md)

By default AdapTable stringifies the AdapTable State and puts it into localStorage using `adaptableStateKey` (which defaults to `adaptableId` if you omit it).

If you omit `persistState`, that localStorage write is used. Provide the function when you want remote (or otherwise custom) persistence.

The function is of type [`AdaptablePersistStateFunction`](https://www.adaptabletools.com/docs/reference/adaptablepersiststatefunction.md):

```ts
export interface AdaptablePersistStateFunction {
  (
    state: AdaptablePersistentState, adaptableStateFunctionConfig: AdaptableStateFunctionConfig
  ): Promise<unknown>;
}
```

The function receives a [`AdaptableStateFunctionConfig`](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md) object defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [actionName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#actionname) | `string` | Name of the action that triggered the state change. |
| [adaptableApi](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableapi) | [`AdaptableApi`](https://www.adaptabletools.com/docs/reference/adaptableapi.md) | Adaptable API |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |
| [adaptableId](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableid) | `string` | Id of current Adaptable instance |
| [adaptableStateKey](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablestatekey) | `string` | State Key being used |
| [previousState](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#previousstate) | [`AdaptablePersistentState`](https://www.adaptabletools.com/docs/reference/adaptablepersistentstate.md) | Previous (persistent) state before the action was applied.<br/>This is useful for comparing changes or reverting if necessary. |
| [userName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#username) | `string` | current Adaptable user |

This function is generally used in conjunction with [loadState](#loadstate) - the other side of the persistence mechanism

The persistence (dehydration) flow is: `saveState` -> `persistState`.

Use `saveState` to adjust the state about to be persisted; whatever that returns is passed to `persistState`

This is the place to apply a custom storage format - e.g. wrap the state in an envelope, compress or encrypt it. The matching [loadState](#loadstate) is expected to undo it.

This function should be **asynchronous** and return a `Promise`; the resolved value is ignored

### Clear State

### `clearState`

Allows clearing of remote Adaptable State

  [`AdaptableClearStateFunction`](https://www.adaptabletools.com/docs/reference/adaptableclearstatefunction.md)

This is an optional function which will clear out any saved remote state.

It is only invoked in one place in AdapTable — inside the `reloadInitialState` function in [State API](https://www.adaptabletools.com/docs/technical-reference-adaptable-state/index.md)

If you omit `clearState`, AdapTable removes the localStorage entry for `adaptableStateKey`

The function is of type [`AdaptableClearStateFunction`](https://www.adaptabletools.com/docs/reference/adaptableclearstatefunction.md):

```ts
export interface AdaptableClearStateFunction {
  (adaptableStateFunctionConfig: AdaptableStateFunctionConfig): Promise<any>;
}
```

The function receives a [`AdaptableStateFunctionConfig`](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md) object defined as follows:

| Property | Type | Description |
| --- | --- | --- |
| [actionName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#actionname) | `string` | Name of the action that triggered the state change. |
| [adaptableApi](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableapi) | [`AdaptableApi`](https://www.adaptabletools.com/docs/reference/adaptableapi.md) | Adaptable API |
| [adaptableContext](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablecontext) | `any` | Custom application Context provided in `AdaptableOptions.adaptableContext` |
| [adaptableId](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptableid) | `string` | Id of current Adaptable instance |
| [adaptableStateKey](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#adaptablestatekey) | `string` | State Key being used |
| [previousState](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#previousstate) | [`AdaptablePersistentState`](https://www.adaptabletools.com/docs/reference/adaptablepersistentstate.md) | Previous (persistent) state before the action was applied.<br/>This is useful for comparing changes or reverting if necessary. |
| [userName](https://www.adaptabletools.com/docs/reference/adaptablestatefunctionconfig.md#username) | `string` | current Adaptable user |

```ts
adaptableOptions = {
  stateOptions: {
    clearState: (config) => {
      return remoteStore.delete(config.adaptableStateKey);
    },
  },
};
```

**Example: Remote State Persistence**

Stores AdapTable State via custom `loadState` / `persistState` (mock remote store)

 

- This example shows how to load and persist state through custom State Options
- The demo uses a mock remote service (async + separate storage namespace) so the pattern is clear without an external backend
- In production you would call your own API from the same functions (e.g. Supabase, Firebase, S3, etc.)

In this demo we implement `loadState` and `persistState` against a mock remote persistence service. The call sites are the same as for a real datastore.

<b>Note:</b> State is keyed by `AdaptableStateKey`. Changing the key loads a different persisted state (or the Initial State if none exists yet).

* Loading state - using `loadState` in State Options:

```ts
/**
 * loadState returns a Promise that resolves with the state object
 * retrieved from your remote source.
 */
loadState: (config: AdaptableStateFunctionConfig) => {
    return remotePersistenceService.loadAdaptableState(config.adaptableStateKey);
}
```

* Persisting state - using `persistState` in State Options:

```ts
/**
 * persistState receives the state to store.
 * By default AdapTable uses localStorage; replace this with your remote API.
 * If using Supabase it would be something like:
 *   supabase.from('adaptable_state').upsert({ state_key, state_value })
 */
persistState: (
    state: AdaptablePersistentState,
    config: AdaptableStateFunctionConfig
) => {
    return remotePersistenceService.persistAdaptableState(
        state,
        config.adaptableStateKey,
        config.userName
    );
}
```

- Make any changes to the AdapTable State (e.g. move a column) and then click **Refresh Page**: your changes will be retained
- Change the `AdaptableStateKey` and click **Set Key & Refresh State**: the grid will load that key's state (or Initial State if none exists yet)
- Going back to the previous `AdaptableStateKey` will restore the previous state

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

const remotePersistenceService = new MockRemotePersistenceService();

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Remote State Persistence',
  // Bump this when Initial State / demo chrome changes, so old mock saves don't hide updates
  adaptableStateKey: '101',
  stateOptions: {
    /**
     * Load state from a remote source.
     * This demo uses a mock service; in production call your API instead.
     */
    loadState: (config: AdaptableStateFunctionConfig) => {
      return remotePersistenceService.loadAdaptableState(
        config.adaptableStateKey
      );
    },

    /**
     * Persist state changes to a remote source.
     * By default AdapTable uses localStorage; here we show a custom remote path.
     */
    persistState: (
      state: AdaptablePersistentState,
      config: AdaptableStateFunctionConfig
    ) => {
      return remotePersistenceService.persistAdaptableState(
        state,
        config.adaptableStateKey,
        config.userName
      );
    },
  },
  dashboardOptions: {
    customToolbars: [
      {
        name: 'StateKeyConfigInput',
        render: ({adaptableApi}: {adaptableApi: AdaptableApi}) => {
          const stateKeyValue = adaptableApi.optionsApi.getAdaptableStateKey();
          return `
                <label style="color:#f5f5f5;font-weight:600;margin-right:0.5rem;">AdapTable State Key:</label>
                <input type="text" id="stateKeyValueInput" value="${stateKeyValue}" style="width:8rem;padding:0.35rem 0.5rem;border:1px solid #333;border-radius:4px;background:#fff;color:#111;font-size:1rem;font-weight:600;">
        `;
        },
      },
      {
        name: 'StateKeyConfigButton',
        toolbarButtons: [
          {
            label: 'Set Key & Refresh State',
            buttonStyle: {
              tone: 'info',
              variant: 'raised',
            },
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const element: any =
                document.getElementById('stateKeyValueInput');
              const stateKeyValue = element!.value;
              if (stateKeyValue) {
                context.adaptableApi.stateApi.setAdaptableStateKey(
                  stateKeyValue
                );
              }
            },
          },
        ],
      },
      {
        name: 'RefreshPageButton',
        toolbarButtons: [
          {
            label: 'Refresh Page',
            buttonStyle: {
              tone: 'neutral',
              variant: 'raised',
            },
            onClick: () => {
              // Reloads the demo so users can verify persisted state without
              // refreshing the browser / Sandpack manually.
              window.location.reload();
            },
          },
        ],
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'State Settings',
          Toolbars: [
            'StateKeyConfigInput',
            'StateKeyConfigButton',
            'RefreshPageButton',
          ],
        },
      ],
      PinnedToolbars: ['Layout'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-github_stars',
          Rule: '[github_stars] > 1000',
          Style: {
            BackColor: 'var(--ab-color-palette-21)',
            ForeColor: 'var(--ab-color-palette-13)',
          },
          Scope: {
            ColumnIds: ['github_stars'],
          },
        },
      ],
    },
    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',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
        },
        {
          Name: 'Pivot Layout',
          PivotColumns: ['license'],
          PivotGroupedColumns: ['language'],
          PivotAggregationColumns: [
            {ColumnId: 'github_watchers', AggFunc: 'sum'},
            {ColumnId: 'github_stars', AggFunc: 'sum'},
          ],
        },
      ],
    },
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  adaptableApi.eventApi.on('AdaptableStateChanged', stateChangedEvent => {
    if (stateChangedEvent.actionName === 'LOAD_STATE') {
      adaptableApi.alertApi.showAlert(
        'State Loaded',
        `State loaded successfully: ${stateChangedEvent.adaptableStateKey}`,
        'Success'
      );
    }
  });
};
```

**`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);
  }
}
```

### Debouncing State Changes

By default AdapTable will debounce `saveState` and `persistState` function calls for 400 milliseconds.

This enables grouping multiple sequential calls into single one.

A good analogy might be how lift / elevator doors work

This can be changed using the `debounceStateDelay` property in State Options.

### `debounceStateDelay`

Delay (in ms) to debounce saveState and persistState calls

Provides a debounce delay other than the default of 400ms.

The maximum value allowed is 1000ms, at which point the save/persist calls will happen anyway

```ts {4}
// Wait 3/4 of a second before saving and persisting state
const adaptableOptions: AdaptableOptions = {
    stateOptions: {
        debounceStateDelay: 750
    }
};
``` 

## Managing Multiple States

The Sandpack below is implemented as a **React** app (login control above the grid; switching users re-initialises AdapTable with new `AdaptableOptions`). It runs the same way whichever **framework picker** flavour you have selected.

The `stateOptions`, `entitlementOptions`, and `dashboardOptions` shown in the walkthrough apply equally to AdapTable TypeScript, React, Angular, and Vue — only the surrounding application wiring differs.

**Example: Load & persist state based on user identity/role**

Loading and persisting state based on user identity/role

- This example shows how to load & persist state based on user identity/role. Persistence uses a mock remote service here; in production call your own API from the same functions (e.g. Supabase, Firebase, S3, etc.).
- It also showcases user specific [Permissions (Entitlements)](https://www.adaptabletools.com/docs/handbook-permissioning/index.md) and how to use them to control access to AdapTable features.
- The demo showcases 3 different users:
  - **Guest** (not logged in)
    - any changes they make will not be persisted and will be lost when the page is refreshed
    - all AdapTable features are available but only in read-only mode
  - __Alice__
    - any changes she makes will be persisted and will be available only to her
    - all AdapTable features are available and editable, except for the `StyledColumn` module which is in read-only mode 
  - __Bob__
    - any changes he makes will be persisted and will be available only to him
    - all AdapTable features are available and editable, except for the `Alert` module which is hidden
- The logged in users (`Alice` and `Bob`) can revert to the Initial Adaptable State by clicking the `Reset State` button in the Dashboard.
### Expand to see how the State Management and Entitlements is configured

__1.__ The current user information is loaded/set __before AdapTable is initialised__
 - in this case (a React app) in a local state variable called `currentUser`
__2.__ The Initial Adaptable State is set based on the current user information
```ts {4,16}
export const buildAdaptableState = (userName: 'Alice' | 'Bob' | 'GUEST') => {
  const initialConfigForUser = INITIAL_CONFIGS[userName];
  // merge common config with user specific config
  const initialConfig = {
    ...COMMON_CONFIG,
    ...initialConfigForUser,
  };
  // the rest of AdaptbleOptions is the same for all users
  // we handle the user specific behaviour via callbacks
  const adaptableOptions: AdaptableOptions = {
    primaryKey: 'id',
    adaptableId: 'User Specific State Demo',
    userName: userName,
    adaptableStateKey: 'docs/userSpecificStateDemo',
    initialState: initialConfig,
    // ...
  };
  // ...
};
```
__3.__ The two main state management functions (`loadState` and `persistState`) are implemented (overwriting the default ones based on `localStorage`):
  - non-logged in users (`Guest`) will not have their state persisted at all
  - logged in users (`Alice` and `Bob`) will have their state persisted via the mock remote service (swap for your API in production)
  - the state key is derived from the username, ensuring that each user has their own distinct state
```ts {2,8,12,18}
   stateOptions: {
      loadState: (config: AdaptableStateFunctionConfig) => {
        if (config.userName === 'GUEST') {
          // no persistent state for non-logged in users
          return Promise.resolve({});
        }
        // state key is based on user name
        const stateKey = `${config.adaptableStateKey}/${config.userName}`;
        return remotePersistenceService.loadAdaptableState(stateKey);
      },
      persistState: (state: any, config: AdaptableStateFunctionConfig) => {
        if (config.userName === 'GUEST') {
          // no persistent state for non-logged in users
          return Promise.resolve();
        }
        // state key is based on user name
        const stateKey = `${config.adaptableStateKey}/${config.userName}`;
        return remotePersistenceService.persistAdaptableState(
          state,
          stateKey,
          config.userName
        );
      }
``` 
__4.__ The `Clear state` button which is available to logged in users (`Alice` and `Bob`) simply makes use of the extensive Adaptable API:
```ts {3,4,9,13}
onClick: (_button, context) => {
    // clear remote state
    // alternatively, we could also provide a `StateOptions.clearState()` function with the same implementation
    // if provided, it will be called automatically by the `reloadInitialState()` function
    const optionsApi = context.adaptableApi.optionsApi;
    const stateKey = `${optionsApi.getAdaptableStateKey()}/${
       context.userName
    }`;
    remotePersistenceService.clearAdaptableState(stateKey, context.userName);
    // reload local state
    const stateApi = context.adaptableApi.stateApi;
    stateApi.reloadInitialState();
}
```
__5.__ The `Entitlements` are configured based on the current user information:
```ts {2,8}
    entitlementOptions: {
      defaultAccessLevel: context => {
        if (context.userName === 'GUEST') {
          return 'ReadOnly';
        }
        return 'Full';
      },
      moduleEntitlements: context => {
        if (
          context.userName === 'Alice' &&
          context.adaptableModule === 'StyledColumn'
        ) {
          return 'ReadOnly';
        }
        if (context.userName === 'Bob' && context.adaptableModule === 'Alert') {
          return 'Hidden';
        }
        return context.defaultAccessLevel;
      }
    }
```

- Log in as `Alice` or `Bob` to see how the state is persisted distinctively for each user by making various changes to the grid and then refreshing the page
  - e.g. change the current Layout (sorting/adding/hiding columns), add a new FormatColumn, etc.
- Reset the state by clicking the `Reset State` button in the Dashboard at any time
- Navigate to the `StyledColumn` module and try to edit the existing style (only `Alice` will not be able to do this)

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

```text
src/
  agGridModules.ts                 [template]
  App.tsx
  buildAdaptableState.ts
  columnDefs.ts                    [template]
  gridOptions.ts                   [template]
  index.tsx                        [template]
  MockRemotePersistenceService.ts
  onAdaptableReady.ts              [template]
  rowData.ts                       [template]
  SelectUserComponent.tsx
  styles.css                       [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#react).

**`src/App.tsx`**

```ts
import * as React from 'react';
import {useState} from 'react';
import {
  Adaptable,
  AdaptableApi,
  AdaptableReadyInfo,
} from '@adaptabletools/adaptable-react-aggrid';

// import adaptable css
import '@adaptabletools/adaptable-react-aggrid/index.css';
// import aggrid themes (using Balham theme)

import './styles.css';

import {onAdaptableReady} from './onAdaptableReady';
import {gridOptions} from './gridOptions';
import {agGridModules} from './agGridModules';
import {buildAdaptableState} from './buildAdaptableState';
import {SelectUserComponent} from './SelectUserComponent';

const App: React.FunctionComponent = () => {
  const adaptableApiRef = React.useRef<AdaptableApi>(null);

  const availableUsers = ['Alice', 'Bob'];
  const [currentUser, setCurrentUser] = useState<'Alice' | 'Bob' | 'GUEST'>(
    'GUEST'
  );

  const adaptableOptions = buildAdaptableState(currentUser);

  const agGridOptions = {...gridOptions};

  return (
    <div style={{display: 'flex', flexFlow: 'column', height: '100vh'}}>
      <SelectUserComponent
        availableUsers={availableUsers}
        onCurrentUserChange={(user: any) => {
          setCurrentUser(user || 'GUEST');
        }}></SelectUserComponent>
      <div key={currentUser} style={{height: '100%'}}>
        <Adaptable.Provider
          gridOptions={agGridOptions}
          adaptableOptions={adaptableOptions}
          modules={[...agGridModules]}
          onAdaptableReady={(adaptableReadyInfo: AdaptableReadyInfo) => {
            // save a reference to adaptable api
            adaptableApiRef.current = adaptableReadyInfo.adaptableApi;
            onAdaptableReady(adaptableReadyInfo);
          }}>
          <Adaptable.UI
            style={
              {
                flex: 'none',
                '--ab-dashboard-header__background':
                  currentUser === 'Alice'
                    ? '#522673'
                    : currentUser === 'Bob'
                      ? '#26736c'
                      : '#2966a8',
              } as React.CSSProperties
            }
          />
          <Adaptable.AgGridReact />
        </Adaptable.Provider>
      </div>
    </div>
  );
};
export default App;
```

**`src/buildAdaptableState.ts`**

```ts
import {
  AdaptableOptions,
  AdaptableStateFunctionConfig,
  InitialState,
} from '@adaptabletools/adaptable-react-aggrid';
import {MockRemotePersistenceService} from './MockRemotePersistenceService';

const remotePersistenceService = new MockRemotePersistenceService();

export const buildAdaptableState = (userName: 'Alice' | 'Bob' | 'GUEST') => {
  const initialStateForUser = INITIAL_STATES[userName];
  // merge common state with user specific state
  const initialState = {
    ...COMMON_STATE,
    ...initialStateForUser,
  };

  // the rest of AdaptbleOptions is the same for all users
  // we handle the user specific behaviour via callbacks
  const adaptableOptions: AdaptableOptions = {
    primaryKey: 'id',
    adaptableId: 'User Specific State Demo',
    userName: userName,
    adaptableStateKey: 'docs/userSpecificStateDemo',
    initialState,
    stateOptions: {
      loadState: (config: AdaptableStateFunctionConfig) => {
        if (config.userName === 'GUEST') {
          // no persistent state for non-logged in users
          return Promise.resolve({});
        }
        // state key is based on user name
        const stateKey = `${config.adaptableStateKey}/${config.userName}`;

        return remotePersistenceService.loadAdaptableState(stateKey);
      },
      persistState: (state: any, config: AdaptableStateFunctionConfig) => {
        if (config.userName === 'GUEST') {
          // no persistent state for non-logged in users
          return Promise.resolve();
        }
        // state key is based on user name
        const stateKey = `${config.adaptableStateKey}/${config.userName}`;
        return remotePersistenceService.persistAdaptableState(
          state,
          stateKey,
          config.userName
        );
      },
    },
    entitlementOptions: {
      defaultAccessLevel: context => {
        if (context.userName === 'GUEST') {
          return 'ReadOnly';
        }
        return 'Full';
      },
      moduleEntitlements: context => {
        if (
          context.userName === 'Alice' &&
          context.adaptableModule === 'StyledColumn'
        ) {
          return 'ReadOnly';
        }
        if (context.userName === 'Bob' && context.adaptableModule === 'Alert') {
          return 'Hidden';
        }
        return context.defaultAccessLevel;
      },
    },
    dashboardOptions: {
      buttonsLocation: 'left',
      customDashboardButtons: [
        {
          label: (_button, context) =>
            `Reset remote state for ${context.userName}`,
          onClick: (_button, context) => {
            // clear remote state
            // alternatively, we could also provide a `StateOptions.clearState()` function with the same implementation
            // if provided, it will be called automatically by the `reloadInitialState()` function
            const optionsApi = context.adaptableApi.optionsApi;
            const stateKey = `${optionsApi.getAdaptableStateKey()}/${
              context.userName
            }`;
            remotePersistenceService.clearAdaptableState(
              stateKey,
              context.userName
            );

            // reload local state
            const stateApi = context.adaptableApi.stateApi;
            stateApi.reloadInitialState();
          },
          buttonStyle: {
            variant: 'raised',
            tone: 'warning',
          },
          hidden: (_button, context) => {
            return context.userName === 'GUEST';
          },
        },
      ],
    },
  };

  return adaptableOptions;
};

const INITIAL_STATES: Record<'Alice' | 'Bob' | 'GUEST', InitialState> = {
  Alice: {
    Theme: {
      Revision: 1,
      CurrentTheme: 'light',
    },
    Dashboard: {
      Revision: 1,
      DashboardTitle: 'Alice Grid Data',
      Tabs: [
        {
          Name: 'Default',
          Toolbars: ['Layout', 'Export'],
        },
      ],
      PinnedToolbars: ['GridFilter'],
    },
    Layout: {
      Revision: 1,
      CurrentLayout: 'Popular Frameworks',
      Layouts: [
        {
          Name: 'Popular Frameworks',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'created_at',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'description',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
          ],
          ColumnFilters: [
            {
              ColumnId: 'github_stars',
              Expression: '[github_stars] > 50000',
            },
          ],
        },
      ],
    },
    StyledColumn: {
      Revision: 1,
    
      StyledColumns: [
        {  Name: 'language Badge',
          ColumnId: 'language',
          BadgeStyle: {
            Badges: [
              {
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-17)',
                  ForeColor: 'var(--ab-color-palette-22)',
                },
                Rule: '[language] = "TypeScript"',
              },
              {
                PillStyle: {
                  BackColor: 'var(--ab-color-palette-20)',
                  ForeColor: 'var(--ab-color-palette-13)',
                },
                Rule: '[language] = "JavaScript"',
              },
            ],
          },
        },
      ],
    },
  },
  Bob: {
    Theme: {
      Revision: 1,
      CurrentTheme: 'dark',
    },
    Dashboard: {
      Revision: 1,
      DashboardTitle: 'Bob Grid Data',
      Tabs: [
        {
          Name: 'Default',
          Toolbars: ['Layout', 'Alert'],
        },
      ],
      PinnedToolbars: ['QuickSearch'],
    },
    Layout: {
      Revision: 2,
      CurrentLayout: 'TypeScript Frameworks',
      Layouts: [
        {
          Name: 'JavaScript Frameworks',
          TableColumns: [
            'name',
            'description',
            'github_stars',
            'open_issues_count',
            'github_watchers',
            'updated_at',
            'license',
            'created_at',
            'has_wiki',
            'pushed_at',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          ColumnFilters: [
            {
              ColumnId: 'language',
              Expression: '[language] = "JavaScript"',
            },
          ],
        },
      ],
    },
    StyledColumn: {
      Revision: 1,
      StyledColumns: [
        {
          Name: 'open_issues_count Gradient',
          ColumnId: 'open_issues_count',
          GradientStyle: {
            CellRanges: [
              {
                Min: 'Col-Min',
                Max: 'Col-Max',
                Color: '#a52a2a',
              },
            ],
          },
        },
      ],
    },
  },
  GUEST: {
    Theme: {
      Revision: 1,
      CurrentTheme: 'dark',
    },
    Dashboard: {
      Revision: 1,
      DashboardTitle: 'Guest Grid Data',
    },
    Layout: {
      Revision: 2,
      CurrentLayout: 'Table Layout',
      Layouts: [
        {
          Name: 'Table Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'description',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
        },
      ],
    },
  },
};

const COMMON_STATE: InitialState = {
  FormatColumn: {
    Revision: 1,
    FormatColumns: [
      {
        Name: 'formatColumn-date',
        Scope: {
          DataTypes: ['date'],
        },
        DisplayFormat: {
          Formatter: 'DateFormatter',
          Options: {
            Pattern: 'yyyy-MM-dd',
          },
        },
      },
    ],
  },
  Layout: {
    Revision: 1,
    CurrentLayout: 'Standard Layout',
    Layouts: [
      {
        TableColumns: [],
        Name: 'Standard Layout',
      },
    ],
  },
};
```

**`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);
  }
}
```

**`src/SelectUserComponent.tsx`**

```ts
import React, {ChangeEventHandler, FC, useState} from 'react';

interface SelectUserComponentProps {
  availableUsers: string[];
  onCurrentUserChange: (user?: string) => void;
}
export const SelectUserComponent: FC<SelectUserComponentProps> = ({
  availableUsers,
  onCurrentUserChange,
}) => {
  const [selectedUser, setSelectedUser] = useState<string | undefined>();
  const [currentUser, setCurrentUser] = useState<string | undefined>();

  const handleUserSelect: ChangeEventHandler<HTMLSelectElement> = event => {
    const selectedValue = event.target.value;
    setSelectedUser(selectedValue === '' ? undefined : selectedValue);
  };

  const handleLogin = () => {
    if (selectedUser) {
      setCurrentUser(selectedUser);
      onCurrentUserChange(selectedUser);
    }
  };

  const handleLogout = () => {
    setSelectedUser(undefined);
    setCurrentUser(undefined);
    onCurrentUserChange(undefined);
  };

  return (
    <div>
      <label>Current user:</label>
      <select
        value={selectedUser || ''}
        onChange={handleUserSelect}
        className={'ab-SimpleButton ab-SimpleButton--variant-outlined'}
        disabled={!!currentUser}>
        <option key={'placeholder'} value="" disabled>
          Select a user
        </option>
        {availableUsers.map(user => (
          <option key={user} value={user}>
            {user}
          </option>
        ))}
      </select>
      {currentUser ? (
        <button
          onClick={handleLogout}
          className={
            'ab-SimpleButton ab-SimpleButton--variant-raised ab-SimpleButton--tone-error'
          }>
          Logout
        </button>
      ) : (
        <button
          onClick={handleLogin}
          disabled={!selectedUser}
          className={`ab-SimpleButton ab-SimpleButton--variant-raised ab-SimpleButton--tone-info ${
            !selectedUser ? 'ab-SimpleButton--disabled' : ''
          }`}>
          Login
        </button>
      )}
    </div>
  );
};
```



## Controlling State Persistence

In more advanced use cases, developers wish to control how and when State is persisted.

Their aim is to suppress automatic State Persistence, and to persist state imperatively instead.

There are 2 common scenarios:

- suppressing **all** State Persistence and replacing it with an imperative save function
- suppressing **specific** State Persistence and replacing just that with an imperative save function

A popular use case is to save Layouts manually, on clicking a button, rather than automatically

### Suppressing all Persistence

**Example: Persisting state imperatively**

Custom State Persistence: Suppressing automatic State Persistence and imperatively persisting State

- In this example we show how to suppress the automatic state persistence and imperatively persist the state
- This is useful when you want to control when the state is persisted, e.g. after a user action or a specific event
- This demo uses the [Adaptable Context](https://www.adaptabletools.com/docs/dev-guide-tutorial-providing-adaptable-context/index.md) to handle the interaction, but you can use any other mechanism, including your own application logic/state management

- Perform any changes to the AdapTable State: e.g. change the current Layout (sorting/adding/hiding columns), add a new FormatColumn, etc.
- The changes will be kept client side and will be persisted only when you click the `Persist State` button in the Dashboard
- Refreshing the demo will load the last persisted state, but any changes made since the last persistence will be lost
- The suppressed changes are logged in the console
- Reset the state to the initial value by clicking the `Reset State` button in the Dashboard at any time

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]
  stateOptions.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 {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {
  cleanupPostPersistState,
  customStateOptions,
  forcePersistState,
  getUnsavedChangesCounter,
  updateLastPersistedState,
} from './stateOptions';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom State Persistence: Imperative Persist',
  stateOptions: customStateOptions,
  dashboardOptions: {
    customToolbars: [
      {
        name: 'PersistState',
        toolbarButtons: [
          {
            label: (_button, context) => {
              const {adaptableApi} = context;
              const unsavedStateChangesCounter =
                getUnsavedChangesCounter(adaptableApi);
              return `Persist State (Unsaved Changes =  ${unsavedStateChangesCounter})`;
            },
            onClick: (_button, context) => {
              const {adaptableApi} = context;

              forcePersistState(adaptableApi);

              adaptableApi.stateApi.persistAdaptableState();
            },
            buttonStyle: (_button, context) => {
              const {adaptableApi} = context;
              const hasUnsavedChanged =
                getUnsavedChangesCounter(adaptableApi) > 0;
              return {
                variant: 'raised',
                tone: hasUnsavedChanged ? 'warning' : 'info',
              };
            },
          },
        ],
        title: 'Check console for more infos',
      },
    ],
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_button, context) => {
          const {adaptableApi} = context;

          context.adaptableApi.stateApi.reloadInitialState();

          // reset transient state values
          // relevant only for this demo
          setTimeout(() => {
            const state = adaptableApi.stateApi.getPersistentState();
            updateLastPersistedState(state);
            cleanupPostPersistState(adaptableApi);
          }, 500);
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Default',
          Toolbars: ['Layout', 'PersistState'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-github_stars',
          Rule: '[github_stars] > 1000',
          Style: {
            BackColor: 'var(--ab-color-palette-21)',
            ForeColor: 'var(--ab-color-palette-13)',
          },
          Scope: {
            ColumnIds: ['github_stars'],
          },
        },
      ],
    },
    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',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
        },
      ],
    },
  },
};
```

**`src/stateOptions.ts`**

```ts
import {
  AdaptableApi,
  AdaptablePersistentState,
  AdaptableStateFunctionConfig,
  StateOptions,
} from '@adaptabletools/adaptable';

export let LAST_PERSISTED_STATE: AdaptablePersistentState | null = null;

export const customStateOptions: StateOptions = {
  persistState: (state, adaptableStateFunctionConfig) => {
    const {adaptableApi, adaptableStateKey} = adaptableStateFunctionConfig;

    const forcePersistState = shouldPersistState(adaptableApi);

    if (!forcePersistState) {
      let stateDelta = getStateDelta(state);
      if (stateDelta.trim() !== '') {
        console.log(`Suppressing state persistence!`);

        incrementUnsavedChangesCounter(adaptableApi);

        console.log('State diff: ', stateDelta);
      }

      return Promise.resolve();
    }
    console.log(`Persisting state!`);
    localStorage.setItem(adaptableStateKey, JSON.stringify(state));

    updateLastPersistedState(state);
    cleanupPostPersistState(adaptableApi);

    return Promise.resolve(true);
  },
  loadState: (config: AdaptableStateFunctionConfig) => {
    console.log(`Loading state...`);
    return new Promise(resolve => {
      let state = {} as AdaptablePersistentState;
      try {
        state =
          JSON.parse(
            localStorage.getItem(config.adaptableStateKey) as string
          ) || {};
      } catch (err) {
        console.log('Error loading state', err);
      }

      resolve(state);
    });
  },
};

type CustomStateSaveContext = {
  FORCE_PERSIST?: boolean;
  UNSAVED_CHANGES_COUNTER?: number;
};

export function updateLastPersistedState(state: AdaptablePersistentState) {
  LAST_PERSISTED_STATE = state;
}

export function getStateDelta(adaptableState: AdaptablePersistentState) {
  const lastPersistedState = LAST_PERSISTED_STATE || {};
  return getStateDiffString(lastPersistedState, adaptableState);
}

export function shouldPersistState(adaptableApi: AdaptableApi): boolean {
  return (
    adaptableApi.optionsApi.getAdaptableContext<CustomStateSaveContext>()
      .FORCE_PERSIST === true
  );
}

export function getUnsavedChangesCounter(adaptableApi: AdaptableApi) {
  return (
    adaptableApi.optionsApi.getAdaptableContext<CustomStateSaveContext>()
      .UNSAVED_CHANGES_COUNTER || 0
  );
}

export function incrementUnsavedChangesCounter(adaptableApi: AdaptableApi) {
  const unsavedChanges = getUnsavedChangesCounter(adaptableApi);
  adaptableApi.optionsApi.addToAdaptableContext<CustomStateSaveContext>(
    'UNSAVED_CHANGES_COUNTER',
    unsavedChanges + 1
  );
  adaptableApi.dashboardApi.refreshDashboard();
}

export function forcePersistState(adaptableApi: AdaptableApi) {
  adaptableApi.optionsApi.addToAdaptableContext<CustomStateSaveContext>(
    'FORCE_PERSIST',
    true
  );
}

export function cleanupPostPersistState(adaptableApi: AdaptableApi) {
  adaptableApi.optionsApi.addToAdaptableContext<CustomStateSaveContext>(
    'FORCE_PERSIST',
    false
  );
  adaptableApi.optionsApi.addToAdaptableContext<CustomStateSaveContext>(
    'UNSAVED_CHANGES_COUNTER',
    0
  );
  adaptableApi.dashboardApi.refreshDashboard();
}

/**
 * Browser-safe console diff (Sandpack cannot load Node-oriented `json-diff` /
 * `colors`). Returns '' when both values serialize identically.
 */
function getStateDiffString(before: unknown, after: unknown): string {
  const beforeJson = JSON.stringify(before ?? {}, null, 2);
  const afterJson = JSON.stringify(after ?? {}, null, 2);
  if (beforeJson === afterJson) {
    return '';
  }
  return `--- last persisted\n${beforeJson}\n+++ current\n${afterJson}`;
}
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = ({adaptableApi}: AdaptableReadyInfo) => {
  const state = adaptableApi.stateApi.getPersistentState();
  updateLastPersistedState(state);
};
```

### Suppressing specific Persistence

**Example: Persisting specific state slices imperatively**

Custom State Persistence: Suppressing specific State changes and persisting them imperatively

- In this example we show how to suppress the automatic state persistence of specific state slices (e.g. only Layouts with a specific Tag) and imperatively persist them
- All other state changes will be persisted automatically as usual
- This is useful when you want to control when specific changes are persisted, e.g. Layout changes, but not other changes (e.g. FormatColumns)
- This demo uses the [Adaptable Context](https://www.adaptabletools.com/docs/dev-guide-tutorial-providing-adaptable-context/index.md) to handle the interaction, but you can use any other mechanism, including your own application logic/state management

- Perform any changes to the 'Protected Layout': e.g. sort/filter/hide columns, etc.
  - All changes will NOT be persisted automatically but only when you click the `Persist State` button in the Dashboard
  - Refreshing the demo will load the last persisted state, but any changes made since the last persistence will be lost
  - The suppressed changes are logged in the console
- Perform any changes to the 'Standard Layout': e.g. sort/filter/hide columns, etc.
  - All changes will be persisted automatically as usual
- Any other changes to the AdapTable State will be persisted automatically as usual
- Reset the state to the initial value by clicking the `Reset State` button in the Dashboard at any time

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]
  stateOptions.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 {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {
  customStateOptions,
  forcePersistState,
  PROTECTED_LAYOUT_TAG,
} from './stateOptions';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Custom State Persistence: Specific Changes',
  stateOptions: customStateOptions,
  dashboardOptions: {
    customToolbars: [
      {
        name: 'PersistState',
        toolbarButtons: [
          {
            disabled: (_button, context) => {
              const {adaptableApi} = context;
              const currentLayout = adaptableApi.layoutApi.getCurrentLayout();
              return !currentLayout.Tags?.includes(PROTECTED_LAYOUT_TAG);
            },
            label: (_button, context) => {
              return `Persist State (incl. Protected Layout)`;
            },
            onClick: (_button, context) => {
              const {adaptableApi} = context;

              forcePersistState(adaptableApi);

              adaptableApi.stateApi.persistAdaptableState();
            },
            buttonStyle: (_button, context) => {
              return {
                variant: 'raised',
                tone: 'success',
              };
            },
          },
          {
            label: (_button, context) => {
              return `Print Persisted State to Console`;
            },
            onClick: (_button, context) => {
              const {adaptableApi} = context;
              const state =
                JSON.parse(
                  localStorage.getItem(
                    adaptableApi.optionsApi.getAdaptableStateKey()
                  ) as string
                ) || {};

              console.log(`Current Persisted State:`, state);
            },
            buttonStyle: (_button, context) => {
              return {
                variant: 'raised',
                tone: 'accent',
              };
            },
          },
        ],
        title: 'Check console for more infos',
      },
    ],
    customDashboardButtons: [
      {
        tooltip: 'Reset state',
        icon: {
          name: 'refresh',
        },
        buttonStyle: {
          tone: 'error',
        },
        onClick: (_button, context) => {
          context.adaptableApi.stateApi.reloadInitialState();
        },
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Default',
          Toolbars: ['Layout', 'PersistState'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'formatColumn-github_stars',
          Rule: '[github_stars] > 1000',
          Style: {
            BackColor: 'var(--ab-color-palette-21)',
            ForeColor: 'var(--ab-color-palette-13)',
          },
          Scope: {
            ColumnIds: ['github_stars'],
          },
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Protected Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'github_stars',
            'language',
            'github_watchers',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
        },
        {
          Name: 'Protected Layout',
          Tags: [PROTECTED_LAYOUT_TAG],
          RowGroupedColumns: ['language'],
          TableColumns: [
            'name',
            'github_stars',
            'github_watchers',
            'updated_at',
            'description',
            'created_at',
            'has_wiki',
            'pushed_at',
            'open_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          RowGroupValues: {
            RowGroupDefaultBehavior: 'collapsed',
          },
        },
      ],
    },
  },
};
```

**`src/stateOptions.ts`**

```ts
import {
  AdaptableApi,
  AdaptablePersistentState,
  AdaptableStateFunctionConfig,
  StateOptions,
  Layout,
} from '@adaptabletools/adaptable';

let LAST_PERSISTED_STATE = {} as AdaptablePersistentState;

export const PROTECTED_LAYOUT_TAG = 'Protected';

export const customStateOptions: StateOptions = {
  saveState: (state, adaptableStateFunctionConfig) => {
    const {adaptableApi} = adaptableStateFunctionConfig;

    const forcePersistState = shouldPersistState(adaptableApi);
    // if we are forcing the persist state, we want to save all changes
    // including the protected Layout
    if (forcePersistState) {
      cleanupPostPersistState(adaptableApi);

      return state;
    }

    // otherwise, keep the changes on the protected Layout local only and send the latest persisted state instead
    state.Layout.Layouts = state.Layout.Layouts.map(layout => {
      // for the protected layout, we want to return the last persisted state
      if (layout.Tags?.includes(PROTECTED_LAYOUT_TAG)) {
        const lastPersistedLayoutState =
          LAST_PERSISTED_STATE.Layout?.Layouts.find(
            persistedLayout => persistedLayout.Name === layout.Name
          );
        if (!lastPersistedLayoutState) {
          console.error(`No persisted state found for layout ${layout.Name}`);
          return layout;
        }

        const layoutDiff = getStateDiffString(lastPersistedLayoutState, layout);
        if (layoutDiff.trim() !== '') {
          console.log(`Suppressing protected state persistence:`);
          console.log(layoutDiff);
        }

        return lastPersistedLayoutState;
      }
      // for all other layouts, we want to save the current state
      return layout;
    }) as [Layout, ...Layout[]];

    return state;
  },
  persistState: (state, adaptableStateFunctionConfig) => {
    const {adaptableStateKey} = adaptableStateFunctionConfig;

    console.log(`Persisting state!`);
    localStorage.setItem(adaptableStateKey, JSON.stringify(state));

    updateLastPersistedState(state);

    return Promise.resolve(true);
  },
  loadState: (config: AdaptableStateFunctionConfig) => {
    return new Promise(resolve => {
      let state = {} as AdaptablePersistentState;
      try {
        state =
          JSON.parse(
            localStorage.getItem(config.adaptableStateKey) as string
          ) || {};
      } catch (err) {
        console.log('Error loading state', err);
      }

      updateLastPersistedState(state);

      resolve(state);
    });
  },
};

type CustomStateSaveContext = {
  FORCE_PERSIST?: boolean;
};

export function updateLastPersistedState(state: AdaptablePersistentState) {
  LAST_PERSISTED_STATE = state;
}

export function getStateDelta(adaptableState: AdaptablePersistentState) {
  const lastPersistedState = LAST_PERSISTED_STATE || {};
  return getStateDiffString(lastPersistedState, adaptableState);
}

export function shouldPersistState(adaptableApi: AdaptableApi): boolean {
  return (
    adaptableApi.optionsApi.getAdaptableContext<CustomStateSaveContext>()
      .FORCE_PERSIST === true
  );
}

export function forcePersistState(adaptableApi: AdaptableApi) {
  adaptableApi.optionsApi.addToAdaptableContext<CustomStateSaveContext>(
    'FORCE_PERSIST',
    true
  );
}

export function cleanupPostPersistState(adaptableApi: AdaptableApi) {
  adaptableApi.optionsApi.addToAdaptableContext<CustomStateSaveContext>(
    'FORCE_PERSIST',
    false
  );
  adaptableApi.dashboardApi.refreshDashboard();
}

/**
 * Browser-safe console diff (Sandpack cannot load Node-oriented `json-diff` /
 * `colors`). Returns '' when both values serialize identically.
 */
function getStateDiffString(before: unknown, after: unknown): string {
  const beforeJson = JSON.stringify(before ?? {}, null, 2);
  const afterJson = JSON.stringify(after ?? {}, null, 2);
  if (beforeJson === afterJson) {
    return '';
  }
  return `--- last persisted\n${beforeJson}\n+++ current\n${afterJson}`;
}
```
