Skip to main content

Manager

Managers handle global side effects. They are like watchEffect(), but for the central data store.

The default managers run the asynchronous behavior that Data Client provides, such as fetching and subscriptions. Configure them with getDefaultManagers(), and add your own Managers.

Each Manager implements middleware, which connects it to the store's control flow. init() and cleanup() connect it to the store's lifecycle, for setup and teardown.

type Dispatch = (action: ActionTypes) => Promise<void>;

type Middleware = (controller: Controller) => (next: Dispatch) => Dispatch;

interface Manager {
middleware: Middleware;
cleanup(): void;
init?: (state: State<any>) => void;
}

Lifetimes​

Each store gets its own Managers. A Manager's code lives at one of three lifetimes:

LifetimeLastsHolds
Configthe pageoptions passed to the constructor, like a URL or callbacks
Storeone store, from the managers function to unmountinstance fields about the store, like fetches in flight
Activeinit() to cleanup()timers, connections and listeners

So a constructor only stores its options.

Lifecycle​

middleware​

middleware works like a redux middleware, except that next() returns a Promise.

This promise resolves when the DataClientPlugin store commits the update, so a Manager can await next() to work with the new state.

Middleware can read actions as they are dispatched, and dispatch its own.

init(state)​

Called when Managers start. Start timers and connections here.

cleanup()​

Called when Managers stop. Stop timers and connections here.

Adding managers to Reactive Data Client​

Pass a function to the managers option of DataClientPlugin. It runs once for each app.

main.ts
import { createApp } from 'vue';
import { DataClientPlugin, getDefaultManagers } from '@data-client/vue';
import App from './App.vue';
import MyManager from './MyManager';

const managers = () => [new MyManager(), ...getDefaultManagers()];

const app = createApp(App);
app.use(DataClientPlugin, { managers });
app.mount('#app');

Define the function at module level: it holds only config.

Actions pass through managers in array order. List custom managers before the defaults: NetworkManager resolves most FETCH actions itself instead of passing them on.

Control flow​

Managers connect to the DataClientPlugin store through their lifecycle methods and middleware. They read and dispatch actions, and read the store's state.

Manager flux flowManager flux flow

The job of middleware is to dispatch actions, respond to actions, or both.

Dispatching Actions​

Controller provides type-safe action dispatchers.

import type { Controller, Manager, Middleware } from '@data-client/vue';
import CurrentTime from './CurrentTime';

export default class TimeManager implements Manager {
  declare protected controller: Controller;
  declare protected intervalID?: ReturnType<typeof setInterval>;

  middleware: Middleware = controller => {
    this.controller = controller;
    return next => async action => next(action);
  };

  init() {
    this.intervalID = setInterval(() => {
      this.controller.set(
        CurrentTime,
        { id: 1 },
        { id: 1, time: Date.now() },
      );
    }, 1000);
  }

  cleanup() {
    clearInterval(this.intervalID);
  }
}

Reading and Consuming Actions​

actionTypes includes all constants to distinguish between different actions.

import type { Manager, Middleware } from '@data-client/vue';
import { actionTypes } from '@data-client/vue';

export default class LoggingManager implements Manager {
  middleware: Middleware = controller => next => async action => {
    switch (action.type) {
      case actionTypes.SET_RESPONSE:
        if (action.endpoint.sideEffect) {
          console.info(
            `${action.endpoint.name} ${JSON.stringify(action.response)}`,
          );
          // wait for state update to be committed
          await next(action);
          // get the data from the store, which may be merged with existing state
          const { data } = controller.getResponse(
            action.endpoint,
            ...action.args,
            controller.getState(),
          );
          console.info(`${action.endpoint.name} ${JSON.stringify(data)}`);
          return;
        }
      // actions must be explicitly passed to next middleware
      default:
        return next(action);
    }
  };

  cleanup() {}
}

Inside each case, TypeScript narrows the action's type, so you can access its members safely.

To consume an action, don't call next().

import type {
  Manager,
  Middleware,
  EntityInterface,
} from '@data-client/vue';
import { actionTypes } from '@data-client/vue';
import isEntity from './isEntity';

export default class CustomSubsManager implements Manager {
  declare protected entities: Record<string, EntityInterface>;

  middleware: Middleware = controller => next => async action => {
    switch (action.type) {
      case actionTypes.SUBSCRIBE:
      case actionTypes.UNSUBSCRIBE:
        const { schema } = action.endpoint;
        // only process registered entities
        if (schema && isEntity(schema) && schema.key in this.entities) {
          if (action.type === actionTypes.SUBSCRIBE) {
            this.subscribe(schema.key, action.args[0]?.product_id);
          } else {
            this.unsubscribe(schema.key, action.args[0]?.product_id);
          }

          // consume subscription if we use it
          return Promise.resolve();
        }
      default:
        return next(action);
    }
  };

  cleanup() {}

  subscribe(channel: string, product_id: string) {}
  unsubscribe(channel: string, product_id: string) {}
}

return Promise.resolve(); instead of next(action) stops managers listed after this one from seeing the action.

Types: FETCH, SET, SET_RESPONSE, RESET, SUBSCRIBE, UNSUBSCRIBE, INVALIDATE, INVALIDATEALL, EXPIREALL

Use cases​

Minimal examples for common Manager use cases: