---
title: "2. Live messages"
description: "A message list that updates on every device, and who is online."
url: "https://arkapi.emincanozcan.com/docs/tutorial-messages"
---

# 2. Live messages

A message list that updates on every device, and who is online.

Now the chat itself: a list of messages that stays up to date on every device, without polling or refresh buttons.

## The backend

Make four additions to `chat.api.ts`. Add `online` to the import:

```ts
import { ApiError, caller, online } from 'arkapi/server'
```

Add the message types below the imports:

```ts
export interface Message {
  id: number
  name: string
  text: string
  mine: boolean
}

interface MessageRow {
  id: number
  name: string
  text: string
  mine: number
}
```

Create a `messages` table below the `people` table:

```ts
db.run('create table if not exists messages (id integer primary key, device text not null, text text not null, photo text, at integer not null)')
```

Add the new functions below `setName`:

```ts
export function getMessages(): Message[] {
  const rows = db.query<MessageRow, [string]>(`
    select m.id, coalesce(p.name, 'Announcement') as name, m.text, m.device = ? as mine
    from messages m left join people p on p.device = m.device
    order by m.id desc limit 100`).all(caller().deviceId)
  return rows.reverse().map((row) => ({ id: row.id, name: row.name, text: row.text, mine: row.mine === 1 }))
}

export function sendMessage(text: string): void {
  const clean = text.trim()
  if (clean === '') throw new ApiError('BAD_REQUEST', 'Write something first')
  save(me(), clean, null)
}

export function countOnline(): number {
  return online().length
}

function me(): string {
  const { deviceId } = caller()
  if (!nameOf(deviceId)) throw new ApiError('UNAUTHORIZED', 'Pick a name first')
  return deviceId
}

function save(device: string, text: string, photo: string | null): void {
  db.run('insert into messages (device, text, photo, at) values (?, ?, ?, ?)', [device, text, photo, Date.now()])
}
```

- **`Message` crosses the wire.** Interfaces used by endpoints appear in the generated client under the same name, so the screen imports `Message` too. Plain types work: strings, numbers, booleans, arrays, interfaces, `null` unions and records. Send times as numbers, not `Date`.
- **`mine`** depends on who asks, so each device gets its own answer. ArkAPI notices that `getMessages` reads `caller()` and runs it once per device; queries that do not, like `countOnline`, run once and are shared.
- **`online()`** lists the devices that have the app open right now, so `countOnline` changes when someone opens or closes the app.
- The `photo` column and the `'Announcement'` name are for later chapters; they cost nothing now.

## The screen

Replace `Index.ets`. The name picker is the same as before; what is new are the imports, three pieces of state, the `chat` builder, `bubble` and `send`:

```ets
import { AsyncValue, LiveValue } from 'arkapi'
import { countOnline, getMessages, getName, Message, sendMessage, setName } from './chat.api'

@Entry
@Component
struct Index {
  @State name: LiveValue<string> = new LiveValue(getName)
  @State saving: AsyncValue<string> = new AsyncValue()
  @State nameDraft: string = ''
  @State messages: LiveValue<Message[]> = new LiveValue(getMessages)
  @State online: LiveValue<number> = new LiveValue(countOnline)
  @State sending: AsyncValue<void> = new AsyncValue()
  @State draft: string = ''

  build() {
    Column({ space: 12 }) {
      if (this.name.data === null) {
        LoadingProgress().width(32).color('#8A8A99')
      } else if (this.name.data === '') {
        this.namePicker()
      } else {
        this.chat(this.name.data)
      }
    }
    .width('100%')
    .height('100%')
    .padding(16)
    .justifyContent(FlexAlign.Center)
    .backgroundColor('#101014')
  }

  @Builder
  namePicker() {
    Text('Pick a name').fontSize(22).fontColor('#FFFFFF')
    TextInput({ text: $$this.nameDraft, placeholder: 'Ada' })
      .fontColor('#FFFFFF')
      .placeholderColor('#77778A')
      .backgroundColor('#22222A')
    Button('Join')
      .width('100%')
      .fontColor('#FFFFFF')
      .backgroundColor('#4F6BF5')
      .enabled(!this.saving.loading)
      .onClick(() => { this.saving.run(setName(this.nameDraft)) })
    Text(this.nameError()).fontColor('#FF7B7B')
  }

  nameError(): string {
    if (this.saving.errorCode === 'CONFLICT') {
      return 'Someone already has that name'
    }
    if (this.saving.errorCode === 'BAD_REQUEST') {
      return 'Use 1 to 20 characters'
    }
    return this.saving.error ?? ''
  }

  @Builder
  chat(name: string) {
    Text(`${name} · ${this.online.data ?? 0} online`).fontSize(12).fontColor('#8A8A99')
    List({ space: 8 }) {
      ForEach(this.messages.data ?? [], (message: Message) => {
        ListItem() {
          this.bubble(message)
        }
      }, (message: Message) => `${message.id}`)
    }
    .width('100%')
    .layoutWeight(1)
    .stackFromEnd(true)
    Row({ space: 8 }) {
      TextInput({ text: $$this.draft, placeholder: 'Message' })
        .layoutWeight(1)
        .fontColor('#FFFFFF')
        .placeholderColor('#77778A')
        .backgroundColor('#22222A')
        .onSubmit(() => this.send())
      Button('Send')
        .fontColor('#FFFFFF')
        .backgroundColor('#4F6BF5')
        .enabled(!this.sending.loading)
        .onClick(() => this.send())
    }
  }

  @Builder
  bubble(message: Message) {
    Column({ space: 2 }) {
      Text(message.name).fontSize(11).fontColor('#8A8A99')
      Text(message.text)
        .fontSize(15)
        .fontColor('#FFFFFF')
        .padding({ left: 12, right: 12, top: 8, bottom: 8 })
        .borderRadius(14)
        .backgroundColor(message.mine ? '#4F6BF5' : '#2A2A33')
    }
    .width('100%')
    .alignItems(message.mine ? HorizontalAlign.End : HorizontalAlign.Start)
  }

  send(): void {
    this.sending.run(sendMessage(this.draft)).then(() => {
      if (this.sending.error === null) {
        this.draft = ''
      }
    })
  }
}
```

## What happens when you press Send

1. `sendMessage` runs on the server and inserts a row.
2. Because it is a mutation, ArkAPI re-runs every live query that a screen is showing: `getMessages` for each device, `countOnline` once.
3. Results that changed go down each device's socket. For a list that only grew, only the new items are sent.
4. `this.messages.data` changes and ArkUI redraws the list.

All `LiveValue`s in the app share one socket. If it drops, it reconnects by itself and keeps the last data; `connected` turns false after a few seconds, if you want to show it.

## Try it

Send a message from the app. Then give the terminal a name and talk to yourself:

```sh
curl -X POST http://localhost:3000/api/pages.chat.setName \
  -H 'X-ArkAPI-Device: laptop' -d '{"args": ["Lin"]}'
curl -X POST http://localhost:3000/api/pages.chat.sendMessage \
  -H 'X-ArkAPI-Device: laptop' -d '{"args": ["Hello from the terminal"]}'
```

Lin's message appears on the left, in grey, the moment the second command returns. Skip the `setName` with a new device id and `sendMessage` answers `401` with `Pick a name first`.

Next: [someone is typing](/docs/tutorial-typing.md).
