Real-time Updates

React to data changes using dcupl's event system and update data programmatically with data.set().

Key dcupl Functions

Function Purpose
list.on() Subscribe to list events (returns unsubscribe function)
dcupl.data.set() Add or update data items
dcupl.data.remove() Remove data items
dcupl.update() Apply pending data changes to lists

Listening to List Events

Subscribe to changes on a list with list.on():

const productList = dcupl.lists.create({ modelKey: 'Product' });

// Subscribe to list events
const unsubscribe = productList.on((event) => {
  if (event.type === 'list_updated') {
    console.log('List data changed');
    // Refresh your UI here
  }
});

// Later: cleanup
unsubscribe();

Updating Data with data.set()

Push new or updated items into dcupl:

// Add or update a single item
dcupl.data.set([
  { key: 'prod-1', name: 'Widget', stock: 50 }
], { model: 'Product' });

// Apply changes
await dcupl.update();

Update multiple items at once:

dcupl.data.set([
  { key: 'prod-1', stock: 45 },
  { key: 'prod-2', stock: 120 },
  { key: 'prod-3', stock: 0 }
], { model: 'Product' });

await dcupl.update();

Removing Data

Remove items by key:

dcupl.data.remove([
  { key: 'prod-3' }
], { model: 'Product' });

await dcupl.update();

Complete Flow

Combine event listening with data updates:

import { Dcupl } from '@dcupl/core';

const dcupl = new Dcupl();
await dcupl.init();

const orderList = dcupl.lists.create({ modelKey: 'Order' });

// 1. Listen for changes
orderList.on((event) => {
  if (event.type === 'list_updated') {
    const orders = orderList.catalog.query.items();
    console.log('Orders updated:', orders.length);
  }
});

// 2. Update data (from your data source)
function handleNewOrder(order) {
  dcupl.data.set([order], { model: 'Order' });
  dcupl.update(); // Triggers list_updated event
}

// 3. Update existing item
function updateOrderStatus(orderId, status) {
  dcupl.data.set([{ key: orderId, status }], { model: 'Order' });
  dcupl.update();
}

// 4. Remove item
function deleteOrder(orderId) {
  dcupl.data.remove([{ key: orderId }], { model: 'Order' });
  dcupl.update();
}

Batching Updates

For multiple changes, call dcupl.update() once at the end:

// Queue multiple changes
dcupl.data.set([{ key: 'prod-1', stock: 10 }], { model: 'Product' });
dcupl.data.set([{ key: 'prod-2', stock: 20 }], { model: 'Product' });
dcupl.data.remove([{ key: 'prod-3' }], { model: 'Product' });

// Single update triggers one list_updated event
await dcupl.update();