Skip to main content

Goal

Run a Function whenever a specific state value changes, using a state trigger.

Steps

1. Enable the State worker

iii-config.yaml
workers:
  - name: iii-state
    config:
      adapter:
        name: kv
        config:
          store_method: file_based  # Options: in_memory, file_based
          file_path: ./data/state_store.db  # required for file_based

2. Register the Function

The state trigger fires whenever the watched scope/key pair changes. The handler receives an event with key, new_value, old_value, scope, and event_type properties.
state-watcher.ts
import { registerWorker, Logger } from 'iii-sdk'

const iii = registerWorker(process.env.III_URL ?? 'ws://localhost:49134')

iii.registerFunction('orders::on-status-change', async (event) => {
  const logger = new Logger()
  logger.info('Order status changed', { key: event.key, new_value: event.new_value })
  // ...react to the change here...
  return { handled: true }
})

3. Register the state trigger

Each state trigger watches a single scope/key pair. To react to multiple keys, register a function and trigger for each.
state-trigger.ts
iii.registerTrigger({
  type: 'state',
  function_id: 'orders::on-status-change',
  config: { scope: 'orders', key: 'status' },
})

// Then run iii.trigger() from another function or worker to trigger the state change
await iii.trigger({
  function_id: 'state::set',
  payload: {
    scope: 'orders',
    key: 'status',
    value: { orderId: 'order-123', status: 'shipped' },
  },
})

Result

When any Function writes to the watched scope/key pair via state::set or state::update, the Engine automatically invokes the registered handler with the new value.
For advanced state operations and adapter options, see the State module reference.