# Updating Initial Adaptable State

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

- After go-live, you can still ship design-time updates without wiping the rest of User State
- A numeric `Revision` (or `UpdateStrategy: 'Override'`) replaces an entire section of State
- Alternatively, `UpdateStrategy: 'KeepUserDefined'` refreshes design-time items while keeping user-created ones
- Apply on next load, or at runtime via the State API — no grid remount required

- For first-time setup see [Providing Initial Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md)
- See [Adaptable State Persistence](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-persistence/index.md) and the [State Management Module](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-management/index.md) for additional context

## Why Update Initial State?

[Initial Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-initial-state/index.md) is meant for **first-time** use.

Design-time objects are merged into User State once, then users change and persist their own configuration each time they use their application.

But later you might need to change those design-time defaults.

For instance you might want to add a new Format Column, an updated Custom Sort, a ReadOnly flag — but **without** clearing everything else the user has saved.

That is what the per-section `Revision` property is for.

- Revision is **not** a substitute for first-time Initial State
- Nor is it a full wipe of State (for that use `reloadInitialState` / Clear User State)

## How Revision works

Every User State section implements [`BaseState`](https://www.adaptabletools.com/docs/reference/basestate.md), which includes `Revision` defined as follows:

```ts
Revision?: number | { Key: number; UpdateStrategy: 'Override' | 'KeepUserDefined' };
```

Key Rules:

- Revision is **per section** (e.g. Format Column, Layout); bumping one section leaves other sections alone
- Update runs only if new Revision **Key** (or numeric value) is **higher** than what's already stored in User State
- On load AdapTable compares Initial State to persisted State, applying sections where Revision has increased

The same things happen when you call the runtime merge APIs described below

## Choosing a Strategy

The `UpdateStrategy` choice is between 'Override' or 'KeepUserDefined' and is as follows:

|                                      | Number / `Override`                                       | `KeepUserDefined`                                                            |
| ------------------------------------ | --------------------------------------------------------- | ---------------------------------------------------------------------------- |
| What happens to the section          | Fully **replaced** by Initial State                       | Design-time items **replaced**; user-created items **kept**                  |
| User-created objects in that section | **Lost**                                                  | **Kept**                                                                     |
| Best when                            | You want to reset that Module’s config from Initial State | Users may have added their own objects and you only want to refresh defaults |
| Typical shape                        | `Revision: 2` or `{ Key: 2, UpdateStrategy: 'Override' }` | `Revision: { Key: 2, UpdateStrategy: 'KeepUserDefined' }`                    |

A plain number is shorthand for Override — replace only, no merging of user items

## Replacing Entire Section

Increment (or introduce) a numeric `Revision` on the section you want to replace.

AdapTable swaps (essentially **overrides**) that section in User State for the new Initial State contents.

A number is **replace only** — user-created items in that section are removed

```ts
export default {
  CustomSort: {
    // Replaces the Custom Sort section in User State when Revision 2
    // is higher than the stored value. Other sections stay untouched.
    Revision: 2,
    CustomSorts: [
      {
        Name: 'CustomSort-Rating',
        ColumnId: 'Rating',
        SortedValues: ['AAA', 'AA+', 'AA', 'AA-'], // etc.
      },
    ],
  },
} as InitialState;
```

**Example: Revision — replace a whole section**

Bump a numeric `Revision` to replace one Initial State section while leaving the rest of User State alone

- Starts with Format Column Revision `1` styling `Name` (blue)
- **Add User Format Column** calls the API to create a runtime Format Column on `Language` (green)
- **Apply Revision 2** calls `stateApi.applyInitialState()` — the new Initial State (Format Column Revision `2` containing only `Github Stars` in yellow) is merged into the live user state, no page reload
- Because Revision is a number (Override), the whole Format Column section is replaced — the user `Language` style is removed
- Other sections (e.g. Layout) are unchanged
- **Reset Demo** clears persisted state and reloads the page to start again from Revision 1

- Confirm `Name` is blue
- Click **Add User Format Column** — `Language` turns green
- Click **Apply Revision 2** — only `Github Stars` is styled (yellow); `Name` and user `Language` styles are gone
- Click **Reset Demo** to restore Revision 1

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]
  initialState.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 {
  AdaptableButton,
  AdaptableOptions,
  CustomToolbarButtonContext,
  FormatColumn,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {initialStateRevision1, initialStateRevision2} from './initialState';

const ADAPTABLE_STATE_KEY = 'docs/RevisionOverrideDemo';

const userFormatColumn: FormatColumn = {
  Name: 'formatColumn-language-user',
  Scope: {
    ColumnIds: ['language'],
  },
  Style: {
    BackColor: 'var(--ab-color-palette-20)',
    ForeColor: 'var(--ab-color-palette-13)',
    FontWeight: 'Bold',
  },
};

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Revision Override Demo',
  adaptableStateKey: ADAPTABLE_STATE_KEY,
  initialState: initialStateRevision1,
  dashboardOptions: {
    customToolbars: [
      {
        name: 'RevisionDemo',
        title: 'Revision',
        toolbarButtons: [
          {
            label: 'Add User Format Column',
            buttonStyle: {
              tone: 'neutral',
              variant: 'outlined',
            },
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const formatColumnApi = context.adaptableApi.formatColumnApi;
              if (formatColumnApi.getFormatColumnByName(userFormatColumn.Name)) {
                context.adaptableApi.systemStatusApi.setInfoSystemStatus(
                  'User Format Column already present on Language'
                );
                return;
              }
              formatColumnApi.addFormatColumn(userFormatColumn);
              context.adaptableApi.systemStatusApi.setInfoSystemStatus(
                'Added user Format Column on Language (green) — now Apply Revision 2'
              );
            },
          },
          {
            label: 'Apply Revision 2',
            buttonStyle: {
              tone: 'info',
              variant: 'raised',
            },
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              // Merge the new Initial State into the live user state at runtime.
              // Revision 2 is a plain number (Override), so the whole Format Column
              // section is replaced by Initial State - no page reload.
              context.adaptableApi.stateApi
                .applyInitialState(initialStateRevision2)
                .then(() => {
                  context.adaptableApi.systemStatusApi.setSuccessSystemStatus(
                    'Applied Revision 2 — Format Column section replaced with Github Stars; Name and user Language removed'
                  );
                });
            },
          },
          {
            label: 'Reset Demo',
            buttonStyle: {
              tone: 'warning',
              variant: 'outlined',
            },
            onClick: () => {
              // Demo-only reset: clear persisted state and reload the page so the
              // demo cold-starts fresh from Revision 1. (A full reload guarantees a
              // clean store instance for replaying the revisions from scratch.)
              localStorage.removeItem(ADAPTABLE_STATE_KEY);
              window.location.reload();
            },
          },
        ],
      },
    ],
  },
};
```

**`src/initialState.ts`**

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

const commonState: Pick<
  InitialState,
  'Dashboard' | 'Theme' | 'Layout' | 'FormatColumn'
> = {
  Dashboard: {
    Tabs: [
      {
        Name: 'Demo',
        Toolbars: ['RevisionDemo', 'SystemStatus'],
      },
    ],
  },
  Theme: {CurrentTheme: 'dark'},
  Layout: {
    CurrentLayout: 'Standard Layout',
    Layouts: [
      {
        Name: 'Standard Layout',
        TableColumns: [
          'name',
          'language',
          'github_stars',
          'license',
          'created_at',
          'has_wiki',
          'updated_at',
          'pushed_at',
          'github_watchers',
          'description',
          'open_issues_count',
        ],
        AutoSizeColumns: true,
      },
    ],
  },
};

/** Revision 1 — Format Column on Name (blue) */
export const initialStateRevision1: InitialState = {
  ...commonState,
  FormatColumn: {
    Revision: 1,
    FormatColumns: [
      {
        Name: 'formatColumn-name-initial',
        Scope: {
          ColumnIds: ['name'],
        },
        Style: {
          BackColor: '#1e88e5',
          ForeColor: 'var(--ab-color-palette-14)',
          FontWeight: 'Bold',
        },
      },
    ],
  },
};

/**
 * Revision 2 — whole Format Column section replaced (number Revision = Override).
 * Only Github Stars remains from Initial State; user-created Format Columns are dropped.
 */
export const initialStateRevision2: InitialState = {
  ...commonState,
  FormatColumn: {
    Revision: 2,
    FormatColumns: [
      {
        Name: 'formatColumn-github_stars-initial',
        Scope: {
          ColumnIds: ['github_stars'],
        },
        Style: {
          BackColor: 'var(--ab-color-palette-21)',
          ForeColor: 'var(--ab-color-palette-13)',
          FontWeight: 'Bold',
        },
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = (_info: AdaptableReadyInfo) => {
  // Nothing to do on ready - the toolbar buttons in `adaptableOptions.ts` drive the
  // demo, calling `stateApi.applyInitialState` at runtime (Reset just reloads the page).
};
```

## Keeping User-Created Items

For a more granular update, use the object form:

- `Key` — bump whenever you ship a new version of that section
- `UpdateStrategy: 'KeepUserDefined'` — replace items that came from Initial State; keep items users created at run-time

- AdapTable tells them apart via each Adaptable Object’s `Source` property (`'InitialState'` vs `'User'`).
- Items with `Source !== 'InitialState'` are treated as user-defined and retained

This is the usual way to **re-apply design-time objects on top of already persisted state** — for example change a Format Column background, or mark it [`IsReadOnly`](https://www.adaptabletools.com/docs/reference/adaptableobject.md).

- Re-include **every** Initial State item you still want (with any updated properties)
- An omitted design-time item is **dropped**, even with `KeepUserDefined`
- Only user-created items are preserved automatically

```ts
export default {
  CustomSort: {
    // Replaces design-time Custom Sorts; keeps any user-created ones
    Revision: {Key: 5, UpdateStrategy: 'KeepUserDefined'},
    CustomSorts: [
      {
        Name: 'CustomSort-Rating',
        ColumnId: 'Rating',
        SortedValues: ['AAA', 'AA+', 'AA', 'AA-'], // etc.
      },
    ],
  },
} as InitialState;
```

**Example: Revision — KeepUserDefined**

Use `Revision: { Key, UpdateStrategy: 'KeepUserDefined' }` to apply new Initial State items while retaining user-created ones

- Starts with Format Column Revision `1` styling `Name` (blue)
- **Add User Format Column** calls the API to create a runtime Format Column on `Language` (green)
- **Apply Revision 2** calls `stateApi.applyInitialState()`; Revision `2` lists **empty** Format Column array, so design-time items (`Name` style) are removed but user-created ones are kept; e.g. `Language` (if added)
- **Apply Revision 3** calls `stateApi.applyInitialState()`; Revision `3` adds a new design-time `Github Stars` style (yellow) on top, still keeping user-created Format Columns
- Both merges happen live in the user state — no page reload happens
- **Reset Demo** clears persisted state and reloads the page to start again from Revision 1

- Confirm `Name` is blue
- Click **Add User Format Column** — `Language` turns green
- Click **Apply Revision 2** — `Name` blue is gone, but user `Language` stays green
- Click **Apply Revision 3** — `Github Stars` turns yellow **and** user `Language` remains green
- Click **Reset Demo** to restore Revision 1

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]
  initialState.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 {
  AdaptableButton,
  AdaptableOptions,
  CustomToolbarButtonContext,
  FormatColumn,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';
import {
  initialStateRevision1,
  initialStateRevision2,
  initialStateRevision3,
} from './initialState';

const ADAPTABLE_STATE_KEY = 'docs/RevisionKeepUserDefinedDemo';

const userFormatColumn: FormatColumn = {
  Name: 'formatColumn-language-user',
  Scope: {
    ColumnIds: ['language'],
  },
  Style: {
    BackColor: 'var(--ab-color-palette-20)',
    ForeColor: 'var(--ab-color-palette-13)',
    FontWeight: 'Bold',
  },
};

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Revision KeepUserDefined Demo',
  adaptableStateKey: ADAPTABLE_STATE_KEY,
  initialState: initialStateRevision1,
  dashboardOptions: {
    customToolbars: [
      {
        name: 'RevisionDemo',
        title: 'Revision',
        toolbarButtons: [
          {
            label: 'Add User Format Column',
            buttonStyle: {
              tone: 'neutral',
              variant: 'outlined',
            },
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const formatColumnApi = context.adaptableApi.formatColumnApi;
              if (formatColumnApi.getFormatColumnByName(userFormatColumn.Name)) {
                context.adaptableApi.systemStatusApi.setInfoSystemStatus(
                  'User Format Column already present on Language'
                );
                return;
              }
              formatColumnApi.addFormatColumn(userFormatColumn);
              context.adaptableApi.systemStatusApi.setInfoSystemStatus(
                'Added user Format Column on Language (green) — now Apply Revision 2'
              );
            },
          },
          {
            label: 'Apply Revision 2',
            buttonStyle: {
              tone: 'info',
              variant: 'raised',
            },
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              // Revision 2 lists an empty Format Column array with KeepUserDefined:
              // design-time items (the Name style) are removed, user-created ones kept.
              context.adaptableApi.stateApi
                .applyInitialState(initialStateRevision2)
                .then(() => {
                  context.adaptableApi.systemStatusApi.setSuccessSystemStatus(
                    'Applied Revision 2 — design-time Name style removed; user Language kept'
                  );
                });
            },
          },
          {
            label: 'Apply Revision 3',
            buttonStyle: {
              tone: 'success',
              variant: 'raised',
            },
            onClick: (
              _button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              // Revision 3 adds a new design-time Github Stars style, still keeping
              // user-created Format Columns via UpdateStrategy 'KeepUserDefined'.
              context.adaptableApi.stateApi
                .applyInitialState(initialStateRevision3)
                .then(() => {
                  context.adaptableApi.systemStatusApi.setSuccessSystemStatus(
                    'Applied Revision 3 — Github Stars added; user Language kept'
                  );
                });
            },
          },
          {
            label: 'Reset Demo',
            buttonStyle: {
              tone: 'warning',
              variant: 'outlined',
            },
            onClick: () => {
              // Demo-only reset: clear persisted state and reload the page so the
              // demo cold-starts fresh from Revision 1. (A full reload guarantees a
              // clean store instance for replaying the revisions from scratch.)
              localStorage.removeItem(ADAPTABLE_STATE_KEY);
              window.location.reload();
            },
          },
        ],
      },
    ],
  },
};
```

**`src/initialState.ts`**

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

const commonState: Pick<InitialState, 'Dashboard' | 'Theme' | 'Layout'> = {
  Dashboard: {
    Tabs: [
      {
        Name: 'Demo',
          Toolbars: ['RevisionDemo', 'SystemStatus'],
      },
    ],
  },
  Theme: {CurrentTheme: 'dark'},
  Layout: {
    CurrentLayout: 'Standard Layout',
    Layouts: [
      {
        Name: 'Standard Layout',
        TableColumns: [
          'name',
          'language',
          'github_stars',
          'license',
          'created_at',
          'has_wiki',
          'updated_at',
          'pushed_at',
          'github_watchers',
          'description',
          'open_issues_count',
        ],
        AutoSizeColumns: true,
      },
    ],
  },
};

/** Revision 1 — Format Column on Name (blue) */
export const initialStateRevision1: InitialState = {
  ...commonState,
  FormatColumn: {
    Revision: 1,
    FormatColumns: [
      {
        Name: 'formatColumn-name-initial',
        Scope: {
          ColumnIds: ['name'],
        },
        Style: {
          BackColor: '#1e88e5',
          ForeColor: 'var(--ab-color-palette-14)',
          FontWeight: 'Bold',
        },
      },
    ],
  },
};

/**
 * Revision 2 — KeepUserDefined with an empty array: every design-time Format Column
 * is removed (the Revision 1 `Name` style is dropped), but user-created Format Columns
 * are retained. After this only a user-added `Language` style (if any) remains.
 */
export const initialStateRevision2: InitialState = {
  ...commonState,
  FormatColumn: {
    Revision: {
      Key: 2,
      UpdateStrategy: 'KeepUserDefined',
    },
    FormatColumns: [],
  },
};

/**
 * Revision 3 — KeepUserDefined: a new design-time `Github Stars` Format Column is
 * applied on top, while user-created Format Columns (e.g. `Language`) are still kept.
 */
export const initialStateRevision3: InitialState = {
  ...commonState,
  FormatColumn: {
    Revision: {
      Key: 3,
      UpdateStrategy: 'KeepUserDefined',
    },
    FormatColumns: [
      {
        Name: 'formatColumn-github_stars-initial',
        Scope: {
          ColumnIds: ['github_stars'],
        },
        Style: {
          BackColor: 'var(--ab-color-palette-21)',
          ForeColor: 'var(--ab-color-palette-13)',
          FontWeight: 'Bold',
        },
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

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

export const onAdaptableReady = (_info: AdaptableReadyInfo) => {
  // Nothing to do on ready - the toolbar buttons in `adaptableOptions.ts` drive the
  // demo, calling `stateApi.applyInitialState` at runtime (Reset just reloads the page).
};
```

## Applying at Run-time

Revision merges also run at **startup**.

To deploy a new Initial State (or re-sync) without remounting the grid, use [State API](https://www.adaptabletools.com/docs/technical-reference-adaptable-state/index.md) functions:

| API                                      | What it does                                                                                                                                                 | Use when                                                                                                       |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| `applyInitialState`     | Merges Initial State into the **current** in-memory user state (same Revision rules). If you pass an argument, also updates `AdaptableOptions.initialState`. | You have new Initial State in hand and want to apply it now                                                    |
| `remergePersistedState` | Calls your `StateOptions.loadState`, then merges with the current Initial State. **Throws if you did not provide `loadState`** — there is no localStorage fallback on this path | Persistence changed elsewhere (or Initial State in options was updated) and you want to re-sync without a wipe |
| `reloadInitialState`    | Clears persisted state and reloads from Initial State                                                                                                        | You intentionally want a **full wipe** back to Initial State                                                   |

Both `applyInitialState` and `remergePersistedState` persist afterward and refresh the grid / theme. Prefer them over remounting when shipping section Revisions at runtime.

`remergePersistedState` only works when you supplied `loadState` in State Options. Startup load still falls back to localStorage if `loadState` is omitted; this API does not.

- The [State Management Module](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-management/index.md) UI can also load Initial State from a JSON file
- That replaces state from the file rather than applying a Revision merge

### FAQ

**Does bumping Revision wipe other Modules’ State?**
No. Only the section whose Revision increases is updated; every other section of User State is left alone.

**What if the new Revision Key is not higher than the stored one?**
AdapTable ignores the update for that section.
Always bump `Key` (or the numeric Revision) when you ship a new version.

**Can I use `{ Key, UpdateStrategy: 'Override' }` instead of a number?**
Yes. A plain number is equivalent to Override.
Use the object form when you need `KeepUserDefined`, or when you want the strategy spelled out explicitly.

**How does AdapTable know which items are “user-created”?**
Adaptable Objects carry a `Source` of `'InitialState'` or `'User'`.
For `KeepUserDefined`, items whose `Source` is not `'InitialState'` are kept and concatenated with the new Initial State.
