On this page

Realtime channels

Subscribe to changes, send broadcasts and track presence.

#Postgres changes

JavaScript
stitchdb
  .channel('todos')
  .on('postgres_changes', { event: '*', schema: 'public', table: 'todos' }, (payload) => {
    console.log(payload.eventType, payload.new)
  })
  .subscribe()

#send

JavaScript
const room = stitchdb.channel('room-1')

room.on('broadcast', { event: 'cursor' }, ({ payload }) => moveCursor(payload))
await room.subscribe()

room.send({ type: 'broadcast', event: 'cursor', payload: { x: 120, y: 48 } })

#track and presenceState

JavaScript
const room = stitchdb.channel('room-1')
room.on('presence', { event: 'sync' }, () => console.log(room.presenceState()))
room.subscribe(async (status) => {
  if (status === 'SUBSCRIBED') await room.track({ user: 'ada', online_at: new Date().toISOString() })
})

untrack() removes your presence.

#Subscription status

JavaScript
room.subscribe((status, err) => {
  // 'SUBSCRIBED' | 'TIMED_OUT' | 'CLOSED' | 'CHANNEL_ERROR'
})

#Unsubscribe

JavaScript
await stitchdb.removeChannel(room)
await stitchdb.removeAllChannels()
stitchdb.getChannels()
Was this helpful?