# Zustand

> Browse, edit and time travel your Zustand stores, and call their actions from the desktop app. It is off until you register your stores.

The Zustand panel has three tabs. **State** shows each store’s current state and lets you edit its values. **Changes** lists every change with a diff, and can unwind a store to any of them. **Call** runs a store’s actions with arguments you enter.

[Using Zustand in the desktop app](/docs/desktop/zustand/)

## Setup

**Accepts** `false | ZustandPluginConfig` Opt-in

| Option            | Type                               | Default | Description                                                                               |
| ----------------- | ---------------------------------- | ------- | ----------------------------------------------------------------------------------------- |
| `stores` required | `Record<string, ZustandStoreLike>` | —       | Stores to inspect, keyed by the name the desktop app shows for each one.                  |
| `historyLimit`    | `number`                           | `200`   | How many recent changes to keep per store for the Changes tab and time travel.            |
| `actions`         | `ZustandCallableLike[]`            | `[]`    | Args templates for store actions, built with `callableAction()`, to prefill the Call tab. |

Pass your stores in `stores`. Each key is the name the panel shows for that store:

* index.ts

  ```ts
  import { init } from '@xerlock/client';

  import { useCaseStore, useSuspectStore } from './stores';

  init({
    zustand: {
      stores: {
        case: useCaseStore,
        suspects: useSuspectStore,
      },
    },
  });
  ```

* stores.ts

  ```ts
  import { create } from 'zustand';

  type CaseState = {
    caseNumber: number;
    solved: boolean;
    openCase: (caseNumber: number) => void;
    solve: () => void;
  };

  export const useCaseStore = create<CaseState>()((set) => ({
    caseNumber: 221,
    solved: false,
    openCase: (caseNumber) => set({ caseNumber, solved: false }),
    solve: () => set({ solved: true }),
  }));

  type SuspectState = {
    suspects: string[];
    addSuspect: (name: string) => void;
  };

  export const useSuspectStore = create<SuspectState>()((set) => ({
    suspects: [],
    addSuspect: (name) => set((state) => ({ suspects: [...state.suspects, name] })),
  }));
  ```

`init()` reads `stores` once, so register every store in that call.

### Naming changes

Each change is labelled by the top-level keys it changed, such as `items`. To label it with a name instead, add `xerlockMiddleware()` to the store and pass the name as the third argument to `set`:

```ts
import { xerlockMiddleware } from '@xerlock/client';
import { create } from 'zustand';

type EvidenceState = { items: string[]; addItem: (item: string) => void };

export const useEvidenceStore = create<EvidenceState>()(
  xerlockMiddleware((set) => ({
    items: [],
    addItem: (item) =>
      set((state) => ({ items: [...state.items, item] }), false, 'evidence/addItem'),
  })),
);
```

The name can also be a `{ type }` object, and works the same with `api.setState`. Calls without a name are still labelled by their keys.

With other middleware, such as `devtools` or `persist`, `xerlockMiddleware()` must be the innermost:

```ts
import { xerlockMiddleware } from '@xerlock/client';
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

type EvidenceState = { items: string[]; addItem: (item: string) => void };

export const useEvidenceStore = create<EvidenceState>()(
  devtools(
    persist(
      xerlockMiddleware((set) => ({
        items: [],
        addItem: (item) =>
          set((state) => ({ items: [...state.items, item] }), false, 'evidence/addItem'),
      })),
      { name: 'evidence' },
    ),
  ),
);
```

### Prefilling action arguments

The Call tab finds each store’s actions for you: they are the top-level functions in its state. To prefill an action’s arguments, wrap it with `callable()`:

```ts
import { callable } from '@xerlock/client';
import { create } from 'zustand';

type SuspectState = { suspects: string[]; addSuspect: (name: string) => void };

export const useSuspectStore = create<SuspectState>()((set) => ({
  suspects: [],
  addSuspect: callable(
    (name: string) => set((state) => ({ suspects: [...state.suspects, name] })),
    ['Irene Adler'],
  ),
}));
```

Or keep Xerlock out of the store and register the template in `init()` with `callableAction()`:

```ts
import { callableAction, init } from '@xerlock/client';

import { useCaseStore, useSuspectStore } from './stores';

init({
  zustand: {
    stores: {
      case: useCaseStore,
      suspects: useSuspectStore,
    },
    actions: [callableAction(useSuspectStore, 'addSuspect', ['Irene Adler'])],
  },
});
```

Both check the template against the action’s parameters. A `callableAction()` template wins over a `callable()` one for the same action. A `callableAction()` whose store isn’t in `stores` is ignored, with a warning in the console.

`xerlockMiddleware()`, `callable()` and `callableAction()` do nothing in production builds.

Caution

Update state immutably, as Zustand expects. The SDK keeps each state you replace for diffs and time travel, so changing an object in place changes the history too.

### Shapes

The SDK doesn’t depend on Zustand. Any object with this shape works as a store:

| Member                                                                         | Description                                                                                 |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------- |
| `getState(): unknown`                                                          | Returns the current state.                                                                  |
| `setState(partial: unknown, replace?: boolean): void`                          | Replaces state. Used for edits and time travel, always with `replace: true`.                |
| `subscribe(listener: (state: unknown, previous: unknown) => void): () => void` | Calls the listener with `(state, previous)` after every change, and returns an unsubscribe. |

### Turning it off

Leave out `zustand`, or pass `false`, to hide the Zustand panel for this app.

## Limits and Troubleshooting

* Stores can only be registered in `init()`. A store created later doesn’t appear until `init()` runs again with it.
* **The Zustand panel is missing**: pass `zustand` to `init()`, and check that every value in `stores` is a store. One that isn’t turns the panel off.
* **Changes show keys instead of names**: add `xerlockMiddleware()` to the store, innermost of its middleware.
