Skip to main content

Mobile development · Intermediate · 27 min

Store Larkfield appointments on the phone with expo-sqlite

By Padding · Updated 18 Nov 2026
Expo SDK 58 · expo-sqlite 58.0.18 · Node.js 26 (node:26)

You will have the Larkfield app saving bookings to an SQLite database on the phone, with versioned migrations, bound parameters, all-or-nothing writes and an Appointments tab that updates itself, all covered by Jest tests.

On this page

Part 2 left the Larkfield booking form validating a patient's details and then doing nothing with them. In this part the app keeps every booking in an SQLite database on the phone. Patients can open the Appointments tab on a bus with no signal, or with their data bundle used up, and still see when and where they are expected. Reading from the phone costs no data at all, which matters to anyone on prepaid mobile data.

You use expo-sqlite, which ships with the Expo SDK and is included in Expo Go, so no custom build is needed. You will write a schema that can change safely between app versions, a small data-access module that only ever binds values (never pastes them into SQL), a transaction for bookings that must succeed together, and a screen that refreshes itself when the table changes. The SQL is tested under Jest against an in-memory SQLite database that has the same methods as the real one.

Step 1 · Decide what the phone keeps

Before writing a table, decide what the database is for. A phone can be lost, shared with a family member or backed up to a cloud account, so store only what the patient needs to see without a connection.

The appointments table keeps:

  • the service and practitioner, as both an ID and the name shown at booking time, so the list reads correctly even if the clinic renames a service later
  • the start time, as an ISO 8601 string in UTC (2026-12-02T07:30:00.000Z), which sorts correctly as text and converts to the patient's own time zone for display
  • the patient's name and the reason for the visit, because the patient typed them and expects to see them again
  • a status (booked or cancelled) and the time the row was created

It does not keep:

  • the phone number and date of birth from the form. The clinic needs them, and part 4 sends them to the clinic's server, but the Appointments tab never shows them, so there is no reason to keep a second copy on the phone.
  • sign-in tokens or anything that grants access. An SQLite file is readable by anyone who can read the app's files, for example from an unencrypted backup. Secrets belong in the platform keychain or keystore through expo-secure-store, which a later tutorial covers.
  • small preferences such as the last tab opened. A key-value store suits them better; see save settings with MMKV.

The reason for a visit is health information. The phone's storage encryption protects the file while the phone is off or has not been unlocked since it restarted. After the first unlock, the app's files can be read even while the screen is locked, so treat that encryption as protection against a lost phone that was switched off, not as a lock on the data. If your clinic's rules require more, expo-sqlite can be built with SQLCipher through its useSQLCipher config plugin option, which needs a development build rather than Expo Go.

Check it worked

Write the column list down before the next step: about ten columns, none of which is a token, password, phone number or date of birth. If your list has one of those, move it to the server or to secure storage now, while the schema is still on paper.

Step 2 · Install expo-sqlite and the test database

Install expo-sqlite with npx expo install, which picks the version that matches SDK 58. Then add better-sqlite3 as a development dependency. It is a Node.js SQLite library that the Jest tests use as an in-memory stand-in for the phone's database. Version 13 ships prebuilt binaries for Linux, macOS and Windows inside the npm package, so the install needs no compiler:

Bash
cd ~/larkfield-app-demo
npx expo install expo-sqlite
npm install --save-dev better-sqlite3@13.2.0 @types/better-sqlite3@9.6.0

better-sqlite3 never reaches the app bundle: only test files import it.

Check it worked

Bash
cd ~/larkfield-app-demo
node -e "const p=require('./package.json'); console.log(p.dependencies['expo-sqlite'], p.devDependencies['better-sqlite3'])"

The output is ~58.0.18 ^13.2.0, or a later patch of expo-sqlite 58.

Step 3 · Write the schema as numbered migrations

An app on a phone cannot be migrated by hand. When a patient installs version 1.4 over version 1.2, the app itself must bring their database up to date, without losing the bookings already on it. SQLite has a spare integer in every database file, PRAGMA user_version, which starts at 0. The app uses it as the schema version: migration 1 takes the database from 0 to 1, migration 2 from 1 to 2, and so on. On every start the app runs only the migrations the file has not had yet.

First, describe the few database methods the app uses. expo-sqlite's SQLiteDatabase already has all of them, so it fits this type without any wrapper, and the tests can pass in anything else with the same methods:

Bash
cd ~/larkfield-app-demo
mkdir -p src/db/testing
cat > src/db/types.ts <<'TS'
export type SQLValue = string | number | null

export type RunResult = { lastInsertRowId: number; changes: number }

// The part of expo-sqlite's SQLiteDatabase that the app uses.
// Tests pass an in-memory database with the same methods.
export interface Db {
  execAsync(source: string): Promise<void>
  runAsync(source: string, params: SQLValue[]): Promise<RunResult>
  getFirstAsync<T>(source: string, params: SQLValue[]): Promise<T | null>
  getAllAsync<T>(source: string, params: SQLValue[]): Promise<T[]>
  withTransactionAsync(task: () => Promise<void>): Promise<void>
}
TS

Now the migrations. Each one runs inside a transaction together with the user_version update, so a migration that fails halfway leaves the database exactly as it was, and the app tries again on the next start:

Bash
cd ~/larkfield-app-demo
cat > src/db/migrations.ts <<'TS'
import type { Db } from './types'

type Migration = (db: Db) => Promise<void>

// Entry N takes the database from version N to N + 1.
// Never edit or reorder an entry once it has shipped: add a new one at the end.
export const migrations: Migration[] = [
  // 1: the appointments table
  async (db) => {
    await db.execAsync(`
      CREATE TABLE appointments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        service_id TEXT NOT NULL,
        service_name TEXT NOT NULL,
        practitioner_id TEXT NOT NULL,
        practitioner_name TEXT NOT NULL,
        starts_at TEXT NOT NULL,
        patient_name TEXT NOT NULL CHECK (length(trim(patient_name)) > 0),
        reason TEXT NOT NULL DEFAULT '',
        status TEXT NOT NULL DEFAULT 'booked' CHECK (status IN ('booked', 'cancelled')),
        created_at TEXT NOT NULL
      );
    `)
  },
  // 2: an index for the upcoming list, which filters by status and sorts by time
  async (db) => {
    await db.execAsync(
      'CREATE INDEX appointments_status_starts_at ON appointments (status, starts_at);',
    )
  },
]

export async function migrate(db: Db): Promise<number> {
  const row = await db.getFirstAsync<{ user_version: number }>('PRAGMA user_version', [])
  const current = row?.user_version ?? 0
  if (current > migrations.length) {
    throw new Error(
      `The database is at version ${current}, but this app only knows ${migrations.length}.`,
    )
  }
  for (let version = current; version < migrations.length; version++) {
    const migration = migrations[version]
    const next = version + 1
    await db.withTransactionAsync(async () => {
      await migration(db)
      // PRAGMA cannot take a bound parameter; next is a number this code computed.
      await db.execAsync(`PRAGMA user_version = ${next}`)
    })
  }
  return migrations.length
}

// Runs once when the app opens the database.
export async function prepareDatabase(db: Db): Promise<void> {
  await db.execAsync('PRAGMA journal_mode = WAL')
  await migrate(db)
}
TS

Three choices here are deliberate:

  • The second migration is separate from the first, although you could have put the index in the table definition. That is how a real schema grows: patients who installed the app with only migration 1 get the index on their next update, and new installs run both. Part 4 adds its outbox table as migration 3 in the same way.
  • A database with a higher version than the app knows is refused. This happens when someone installs an older build over a newer one. Running old code against a newer schema could damage the data, so failing loudly is safer.
  • PRAGMA journal_mode = WAL runs outside the transaction, because SQLite cannot change the journal mode inside one. With write-ahead logging, readers do not block a writer and a writer does not block readers, so the screen can read while a booking is being saved.

Check it worked

Bash
cd ~/larkfield-app-demo
ls src/db
grep -c "async (db) =>" src/db/migrations.ts

The listing shows migrations.ts, testing and types.ts, and the count is 2, one for each migration.

Step 4 · Write the data-access module with bound parameters

Every query that includes a value from the patient uses a ? placeholder, and the value travels separately in the parameter array. SQLite then treats it as data, whatever characters it contains. Never build SQL by joining strings with user input: a name such as Ada'); DROP TABLE appointments; -- would become part of the command. expo-sqlite's execAsync does not bind parameters at all, so it is only for fixed SQL such as the migrations.

Columns are renamed with AS in the query, so rows arrive in the app already in camelCase and the rest of the code never sees snake_case:

Bash
cd ~/larkfield-app-demo
cat > src/db/appointments.ts <<'TS'
import type { Db, SQLValue } from './types'

export type AppointmentStatus = 'booked' | 'cancelled'

export type NewAppointment = {
  serviceId: string
  serviceName: string
  practitionerId: string
  practitionerName: string
  startsAt: string // ISO 8601 in UTC, from Date.toISOString()
  patientName: string
  reason: string
}

export type Appointment = NewAppointment & {
  id: number
  status: AppointmentStatus
  createdAt: string
}

// A fixed list of columns written in this file, never user input.
const COLUMNS = `id, service_id AS serviceId, service_name AS serviceName,
  practitioner_id AS practitionerId, practitioner_name AS practitionerName,
  starts_at AS startsAt, patient_name AS patientName, reason, status,
  created_at AS createdAt`

const INSERT = `INSERT INTO appointments
  (service_id, service_name, practitioner_id, practitioner_name,
   starts_at, patient_name, reason, created_at)
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)`

function insertParams(a: NewAppointment, now: Date): SQLValue[] {
  return [
    a.serviceId,
    a.serviceName,
    a.practitionerId,
    a.practitionerName,
    a.startsAt,
    a.patientName.trim(),
    a.reason.trim(),
    now.toISOString(),
  ]
}

export async function addAppointment(db: Db, a: NewAppointment, now = new Date()) {
  const result = await db.runAsync(INSERT, insertParams(a, now))
  return result.lastInsertRowId
}

// A course of sessions is saved together or not at all.
export async function addAppointments(db: Db, list: NewAppointment[], now = new Date()) {
  const ids: number[] = []
  await db.withTransactionAsync(async () => {
    for (const a of list) {
      const result = await db.runAsync(INSERT, insertParams(a, now))
      ids.push(result.lastInsertRowId)
    }
  })
  return ids
}

export async function listUpcoming(db: Db, now = new Date()) {
  return db.getAllAsync<Appointment>(
    `SELECT ${COLUMNS} FROM appointments
     WHERE status = 'booked' AND starts_at >= ?
     ORDER BY starts_at`,
    [now.toISOString()],
  )
}

export async function getAppointment(db: Db, id: number) {
  return db.getFirstAsync<Appointment>(`SELECT ${COLUMNS} FROM appointments WHERE id = ?`, [id])
}

export async function cancelAppointment(db: Db, id: number) {
  const result = await db.runAsync(
    "UPDATE appointments SET status = 'cancelled' WHERE id = ? AND status = 'booked'",
    [id],
  )
  return result.changes === 1
}
TS

addAppointments is for a physiotherapy course of weekly sessions: the patient books four weeks at once and expects all four or none. Every insert runs inside withTransactionAsync, which commits when the function returns and rolls back if it throws. expo-sqlite's documentation points out that this transaction is not exclusive: any other query that runs while it is open joins it. Keep the code inside short and avoid awaiting unrelated work, such as a network call, in the middle of it.

cancelAppointment marks the row instead of deleting it. Part 4 needs the cancelled row to tell the clinic's server about it.

Check it worked

Bash
cd ~/larkfield-app-demo
grep -c "?" src/db/appointments.ts
grep -n '\${a\.' src/db/appointments.ts || echo "no values pasted into SQL"

The first count is above zero, and the second command prints no values pasted into SQL: the only ${...} in the SQL is the fixed COLUMNS list.

Step 5 · Test the SQL under Jest with an in-memory database

expo-sqlite talks to a native SQLite library that does not exist when Jest runs on your computer. Instead of mocking every query, give the tests a real SQLite database, in memory, with the same five methods as the Db type. Then the tests run the actual SQL: the constraints, the ordering, the transaction and the migrations.

The stand-in lives in src/db/testing, and only tests import it:

Bash
cd ~/larkfield-app-demo
cat > src/db/testing/memory-db.ts <<'TS'
import Database from 'better-sqlite3'
import type { Db, SQLValue } from '../types'

// For tests only: an in-memory SQLite database with the same methods as expo-sqlite.
// Never import this from app code. better-sqlite3 runs in Node.js, not on a phone.
export function openMemoryDb(): Db {
  const sqlite = new Database(':memory:')
  return {
    async execAsync(source: string) {
      sqlite.exec(source)
    },
    async runAsync(source: string, params: SQLValue[]) {
      const result = sqlite.prepare(source).run(...params)
      return { lastInsertRowId: Number(result.lastInsertRowid), changes: result.changes }
    },
    async getFirstAsync<T>(source: string, params: SQLValue[]) {
      return (sqlite.prepare(source).get(...params) as T | undefined) ?? null
    },
    async getAllAsync<T>(source: string, params: SQLValue[]) {
      return sqlite.prepare(source).all(...params) as T[]
    },
    async withTransactionAsync(task: () => Promise<void>) {
      sqlite.exec('BEGIN')
      try {
        await task()
        sqlite.exec('COMMIT')
      } catch (error) {
        sqlite.exec('ROLLBACK')
        throw error
      }
    },
  }
}
TS

The migration tests check a new install, a second start, an upgrade from version 1 with a booking already on it, and the refusal of a newer database:

Bash
cd ~/larkfield-app-demo
cat > src/db/migrations.test.ts <<'TS'
import { migrate, migrations, prepareDatabase } from './migrations'
import { openMemoryDb } from './testing/memory-db'
import type { Db } from './types'

async function schemaVersion(db: Db) {
  const row = await db.getFirstAsync<{ user_version: number }>('PRAGMA user_version', [])
  return row?.user_version
}

async function hasObject(db: Db, type: string, name: string) {
  const rows = await db.getAllAsync<{ name: string }>(
    'SELECT name FROM sqlite_master WHERE type = ? AND name = ?',
    [type, name],
  )
  return rows.length === 1
}

test('a new database is brought to the latest version', async () => {
  const db = openMemoryDb()
  await prepareDatabase(db)
  expect(await schemaVersion(db)).toBe(migrations.length)
  expect(await hasObject(db, 'table', 'appointments')).toBe(true)
})

test('starting the app again runs nothing new', async () => {
  const db = openMemoryDb()
  await migrate(db)
  await expect(migrate(db)).resolves.toBe(migrations.length)
  expect(await schemaVersion(db)).toBe(migrations.length)
})

test('an older database keeps its bookings when it is upgraded', async () => {
  const db = openMemoryDb()
  await migrations[0](db)
  await db.execAsync('PRAGMA user_version = 1')
  await db.runAsync(
    `INSERT INTO appointments (service_id, service_name, practitioner_id,
       practitioner_name, starts_at, patient_name, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)`,
    ['physio', 'Physiotherapy', 'dr-bello', 'Dr Amina Bello',
     '2026-12-01T09:00:00.000Z', 'Chidi Okafor', '2026-11-20T10:00:00.000Z'],
  )
  await migrate(db)
  expect(await schemaVersion(db)).toBe(migrations.length)
  expect(await hasObject(db, 'index', 'appointments_status_starts_at')).toBe(true)
  const rows = await db.getAllAsync<{ patient_name: string }>(
    'SELECT patient_name FROM appointments', [])
  expect(rows).toEqual([{ patient_name: 'Chidi Okafor' }])
})

test('a database from a newer app version is refused', async () => {
  const db = openMemoryDb()
  await db.execAsync(`PRAGMA user_version = ${migrations.length + 1}`)
  await expect(migrate(db)).rejects.toThrow('this app only knows')
})
TS

The data tests check the order of the upcoming list, a name full of SQL, the all-or-nothing course booking and a cancel that finds nothing:

Bash
cd ~/larkfield-app-demo
cat > src/db/appointments.test.ts <<'TS'
import {
  addAppointment,
  addAppointments,
  cancelAppointment,
  getAppointment,
  listUpcoming,
  type NewAppointment,
} from './appointments'
import { prepareDatabase } from './migrations'
import { openMemoryDb } from './testing/memory-db'
import type { Db } from './types'

const now = new Date('2026-11-26T08:00:00.000Z')

function booking(changes: Partial<NewAppointment> = {}): NewAppointment {
  return {
    serviceId: 'gp',
    serviceName: 'GP consultation',
    practitionerId: 'dr-kamau',
    practitionerName: 'Dr Wanjiru Kamau',
    startsAt: '2026-12-02T07:30:00.000Z',
    patientName: 'Ngozi Adeyemi',
    reason: 'Follow-up on blood pressure',
    ...changes,
  }
}

let db: Db
beforeEach(async () => {
  db = openMemoryDb()
  await prepareDatabase(db)
})

test('upcoming appointments come soonest first, without past or cancelled ones', async () => {
  const later = await addAppointment(db, booking({ startsAt: '2026-12-10T09:00:00.000Z' }), now)
  const sooner = await addAppointment(db, booking({ startsAt: '2026-11-28T09:00:00.000Z' }), now)
  await addAppointment(db, booking({ startsAt: '2026-11-01T09:00:00.000Z' }), now)
  const dropped = await addAppointment(db, booking({ startsAt: '2026-12-01T09:00:00.000Z' }), now)
  expect(await cancelAppointment(db, dropped)).toBe(true)

  const list = await listUpcoming(db, now)
  expect(list.map((a) => a.id)).toEqual([sooner, later])
  expect(list[0]).toMatchObject({
    serviceName: 'GP consultation',
    status: 'booked',
    createdAt: now.toISOString(),
  })
})

test('a name containing SQL is stored as plain text', async () => {
  const name = "Ada'); DROP TABLE appointments; --"
  const id = await addAppointment(db, booking({ patientName: name }), now)
  expect((await getAppointment(db, id))?.patientName).toBe(name)
  expect(await listUpcoming(db, now)).toHaveLength(1)
})

test('a course of sessions is saved together or not at all', async () => {
  const weeks = ['2026-12-01', '2026-12-08', '2026-12-15'].map((day) =>
    booking({ serviceId: 'physio', serviceName: 'Physiotherapy', startsAt: `${day}T09:00:00.000Z` }),
  )
  expect(await addAppointments(db, weeks, now)).toHaveLength(3)

  const broken = [
    booking({ startsAt: '2026-12-22T09:00:00.000Z' }),
    booking({ startsAt: '2026-12-29T09:00:00.000Z', patientName: '   ' }),
  ]
  await expect(addAppointments(db, broken, now)).rejects.toThrow(/CHECK constraint failed/)
  expect(await listUpcoming(db, now)).toHaveLength(3)
})

test('cancelling an appointment that does not exist reports false', async () => {
  expect(await cancelAppointment(db, 999)).toBe(false)
})
TS
npx jest src/db --ci

In the course test, the first row of broken is valid and is inserted before the second one fails its check. The final count of 3 proves the transaction rolled the first row back too.

The stand-in has one limit to keep in mind. Its SQLite library is not the one on the phone, so the version and compile options can differ. The tests prove your SQL and your logic. They do not prove the native driver, which is why the last step runs the app.

Check it worked

Jest reports two test suites and Tests: 8 passed, 8 total. To see a test catch a real mistake, change ORDER BY starts_at to ORDER BY id in src/db/appointments.ts and run npx jest src/db again: the first data test fails, because the later appointment was booked first. Change it back before you continue.

Step 6 · Open the database once for the whole app

SQLiteProvider opens the database file when the app starts, runs your onInit function, and only then renders the screens inside it. Every screen below it gets the same open database from useSQLiteContext(). Passing useSuspense lets a React Suspense boundary show a loading message while the migrations run, and enableChangeListener turns on the change events the Appointments tab uses in the next step:

Bash
cd ~/larkfield-app-demo
cat > src/db/database-provider.tsx <<'TSX'
import { SQLiteProvider } from 'expo-sqlite'
import { Suspense, type ReactNode } from 'react'
import { ActivityIndicator, StyleSheet, Text, View } from 'react-native'

import { prepareDatabase } from './migrations'

export const DATABASE_NAME = 'larkfield.db'

function Opening() {
  return (
    <View style={styles.center}>
      <ActivityIndicator />
      <Text style={styles.text}>Opening your appointments</Text>
    </View>
  )
}

export function DatabaseProvider({ children }: { children: ReactNode }) {
  return (
    <Suspense fallback={<Opening />}>
      <SQLiteProvider
        databaseName={DATABASE_NAME}
        onInit={prepareDatabase}
        options={{ enableChangeListener: true }}
        useSuspense
      >
        {children}
      </SQLiteProvider>
    </Suspense>
  )
}

const styles = StyleSheet.create({
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: 12 },
  text: { fontSize: 16 },
})
TSX

Wrap the root layout's navigator in the provider. The version below is part 1's src/app/_layout.tsx with DatabaseProvider around the Stack; the header style, the anchor setting and the three Stack.Screen entries stay exactly as they were. If you added anything else to the file, keep it, inside DatabaseProvider:

Bash
cd ~/larkfield-app-demo
cat > src/app/_layout.tsx <<'TSX'
import { Stack } from 'expo-router'

import { DatabaseProvider } from '@/db/database-provider'
import { headerOptions } from '@/theme'

export const unstable_settings = { anchor: '(tabs)' }

export default function RootLayout() {
  return (
    <DatabaseProvider>
      <Stack screenOptions={headerOptions}>
        <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
        <Stack.Screen name="appointments/[id]" options={{ title: 'Appointment' }} />
        <Stack.Screen name="+not-found" options={{ title: 'Not found' }} />
      </Stack>
    </DatabaseProvider>
  )
}
TSX

The web version of expo-sqlite runs SQLite as WebAssembly, and Metro has to be told to bundle .wasm files. The browser also needs two headers, Cross-Origin-Embedder-Policy and Cross-Origin-Opener-Policy, before it allows the shared memory that the web build uses. The project has no metro.config.js yet, so create one. If you already have one, add the two marked blocks to it instead:

Bash
cd ~/larkfield-app-demo
cat > metro.config.js <<'JS'
const { getDefaultConfig } = require('expo/metro-config')

const config = getDefaultConfig(__dirname)

// expo-sqlite on the web: bundle the SQLite WebAssembly file
config.resolver.assetExts.push('wasm')

// expo-sqlite on the web: allow SharedArrayBuffer in the development server
config.server.enhanceMiddleware = (middleware) => {
  return (req, res, next) => {
    res.setHeader('Cross-Origin-Embedder-Policy', 'credentialless')
    res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
    middleware(req, res, next)
  }
}

module.exports = config
JS

These headers only apply to the development server. If you host the web build later, set the same two headers on that server too.

Check it worked

Bash
cd ~/larkfield-app-demo
grep -n "DatabaseProvider" src/app/_layout.tsx
node -e "const c=require('./metro.config.js'); console.log(c.resolver.assetExts.includes('wasm'))"

The first command prints the import line and the opening and closing tags, and the second prints true.

Step 7 · Show the appointments and keep the list current

The Appointments tab reads from the database through a small hook. It loads the upcoming list once, then subscribes to expo-sqlite's change events and reloads whenever a row in appointments is inserted, updated or deleted. A booking made on the Book tab, or a cancellation on this tab, appears without any refresh button and without passing data between screens:

Bash
cd ~/larkfield-app-demo
cat > src/db/use-upcoming-appointments.ts <<'TS'
import { addDatabaseChangeListener, useSQLiteContext } from 'expo-sqlite'
import { useEffect, useState } from 'react'

import { listUpcoming, type Appointment } from './appointments'

export function useUpcomingAppointments() {
  const db = useSQLiteContext()
  const [appointments, setAppointments] = useState<Appointment[]>([])
  const [error, setError] = useState<Error | null>(null)

  useEffect(() => {
    let active = true
    const load = () => {
      listUpcoming(db).then(
        (rows) => {
          if (active) {
            setAppointments(rows)
            setError(null)
          }
        },
        (e: Error) => {
          if (active) setError(e)
        },
      )
    }
    load()
    const subscription = addDatabaseChangeListener((event) => {
      if (event.tableName === 'appointments') load()
    })
    return () => {
      active = false
      subscription.remove()
    }
  }, [db])

  return { appointments, error }
}
TS

Replace the Appointments tab screen from part 1 with one that uses it. The time is shown in the phone's own language and time zone, so a patient in Lagos and one in Nairobi each see their local time from the same UTC value:

Bash
cd ~/larkfield-app-demo
cat > "src/app/(tabs)/appointments.tsx" <<'TSX'
import { useSQLiteContext } from 'expo-sqlite'
import { Alert, FlatList, Pressable, StyleSheet, Text, View } from 'react-native'

import { cancelAppointment, type Appointment } from '@/db/appointments'
import { useUpcomingAppointments } from '@/db/use-upcoming-appointments'
import { colours } from '@/theme'

function formatWhen(iso: string) {
  return new Date(iso).toLocaleString(undefined, {
    weekday: 'short',
    day: 'numeric',
    month: 'short',
    hour: '2-digit',
    minute: '2-digit',
  })
}

export default function AppointmentsScreen() {
  const db = useSQLiteContext()
  const { appointments, error } = useUpcomingAppointments()

  function confirmCancel(item: Appointment) {
    Alert.alert('Cancel this appointment?', `${item.serviceName}, ${formatWhen(item.startsAt)}`, [
      { text: 'Keep it', style: 'cancel' },
      { text: 'Cancel appointment', style: 'destructive', onPress: () => cancelAppointment(db, item.id) },
    ])
  }

  if (error) {
    return (
      <View style={styles.center}>
        <Text style={styles.body}>Your appointments could not be read. Close the app and open it again.</Text>
      </View>
    )
  }

  return (
    <FlatList
      data={appointments}
      keyExtractor={(item) => String(item.id)}
      style={styles.screen}
      contentContainerStyle={styles.list}
      ListEmptyComponent={
        <Text style={styles.body}>No upcoming appointments. Book one from the Book tab.</Text>
      }
      renderItem={({ item }) => (
        <View style={styles.card}>
          <Text style={styles.when}>{formatWhen(item.startsAt)}</Text>
          <Text style={styles.body}>
            {item.serviceName} with {item.practitionerName}
          </Text>
          <Pressable
            accessibilityRole="button"
            accessibilityLabel={`Cancel ${item.serviceName} on ${formatWhen(item.startsAt)}`}
            onPress={() => confirmCancel(item)}
            style={styles.cancel}
          >
            <Text style={styles.cancelText}>Cancel</Text>
          </Pressable>
        </View>
      )}
    />
  )
}

const styles = StyleSheet.create({
  screen: { backgroundColor: colours.canvas },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24, backgroundColor: colours.canvas },
  list: { padding: 16, gap: 12 },
  card: { padding: 16, gap: 6, borderRadius: 12, backgroundColor: colours.surface, borderWidth: 1, borderColor: colours.line },
  when: { fontSize: 18, fontWeight: '700', color: colours.ink },
  body: { fontSize: 16, color: colours.text },
  cancel: { alignSelf: 'flex-start', minHeight: 44, justifyContent: 'center' },
  cancelText: { fontSize: 16, color: colours.danger },
})
TSX

The cards no longer link to part 1's detail screen, src/app/appointments/[id].tsx. That screen still reads the two sample appointments in src/data/appointments.ts, and a booking from the database has an ID such as 1 that the sample data does not know, so a link would only open "There is no appointment 1." Leave the detail screen and the sample file in place: part 6 uses appointment 42 to try links into the app. When you want a detail screen for real bookings, change [id].tsx to load the row with getAppointment(db, Number(id)) from @/db/appointments and wrap each card in a Link again.

Last, save the booking. The database needs IDs and a real start time, but part 2's time screen passes only two display strings to the details screen, the service name and the slot label (Wed 2 Dec, 09:30), and part 1's slots have no date at all. Three changes fix that.

First, give each slot a start time. Part 1's src/data/clinic.ts stays as it is; the times go in a new file next to it, keyed by slot ID, with the clinic's UTC offset (Lagos, +01:00):

Bash
cd ~/larkfield-app-demo
cat > src/data/slot-times.ts <<'TS'
// When each slot in clinic.ts starts, in the clinic's time zone (UTC+1).
// clinic.ts only has a label for display; the database stores a real time.
export const slotStartsAt: Record<string, string> = {
  'okafor-1': '2026-12-02T09:30:00+01:00',
  'okafor-2': '2026-12-02T11:00:00+01:00',
  'wanjiru-1': '2026-12-03T10:15:00+01:00',
  'wanjiru-2': '2026-12-04T14:00:00+01:00',
  'mensah-1': '2026-12-05T08:45:00+01:00',
}
TS

The sample slots are in December 2026. If that date has passed when you follow along, move these times (and the labels in clinic.ts) into the future, because the Appointments tab hides appointments that have already started.

Second, make the time screen pass IDs instead of display strings. In src/app/(tabs)/book/[serviceId].tsx, the slot's onPress from part 2 reads:

TSX
onPress={() => router.push({ pathname: '/book/details', params: { service: service.name, time: slot.label } })}

Change its params to { serviceId: service.id, practitionerId: practitioner.id, slotId: slot.id }, or run this command, which stops with an error if the line does not match part 2:

Bash
cd ~/larkfield-app-demo
node -e "
const fs = require('fs')
const file = 'src/app/(tabs)/book/[serviceId].tsx'
const from = 'params: { service: service.name, time: slot.label }'
const to = 'params: { serviceId: service.id, practitionerId: practitioner.id, slotId: slot.id }'
const src = fs.readFileSync(file, 'utf8')
if (src.indexOf(from) === -1) throw new Error('Not found in ' + file + ': ' + from)
fs.writeFileSync(file, src.replace(from, to))
"
grep -c "slotId: slot.id" "src/app/(tabs)/book/[serviceId].tsx"

The last command prints 1.

Third, replace part 2's booking details screen, src/app/(tabs)/book/details.tsx. It looks the service, practitioner and slot up from those IDs, shows the same summary line, and hands BookingForm an onSubmit that saves to the database and then opens the Appointments tab. booking is the BookingRequest the form passes in, already checked and trimmed by part 2's schema, so its fields are fullName, phone, dateOfBirth and reason:

Bash
cd ~/larkfield-app-demo
cat > "src/app/(tabs)/book/details.tsx" <<'TSX'
import { Link, Stack, router, useLocalSearchParams } from 'expo-router'
import { useSQLiteContext } from 'expo-sqlite'
import { StyleSheet, Text, View } from 'react-native'

import { BookingForm } from '@/components/BookingForm'
import { findService, practitioners } from '@/data/clinic'
import { slotStartsAt } from '@/data/slot-times'
import { addAppointment } from '@/db/appointments'
import { colours } from '@/theme'

export default function BookingDetailsScreen() {
  const { serviceId, practitionerId, slotId } = useLocalSearchParams<{
    serviceId?: string
    practitionerId?: string
    slotId?: string
  }>()
  const db = useSQLiteContext()
  const service = findService(serviceId)
  const practitioner = practitioners.find((p) => p.id === practitionerId)
  const slot = practitioner?.slots.find((s) => s.id === slotId)
  const startsAt = slot ? slotStartsAt[slot.id] : undefined

  if (!service || !practitioner || !slot || !startsAt) {
    return (
      <View style={styles.screen}>
        <Stack.Screen options={{ title: 'Your details' }} />
        <Text style={styles.summary}>Choose a service and a time first.</Text>
        <Link href="/book" style={styles.link}>
          Choose a service
        </Link>
      </View>
    )
  }

  return (
    <View style={styles.screen}>
      <Stack.Screen options={{ title: 'Your details' }} />
      <Text style={styles.summary}>
        {service.name} · {slot.label} · {practitioner.name}
      </Text>
      <BookingForm
        keyboardOffset={100}
        onSubmit={async (booking) => {
          await addAppointment(db, {
            serviceId: service.id,
            serviceName: service.name,
            practitionerId: practitioner.id,
            practitionerName: practitioner.name,
            startsAt: new Date(startsAt).toISOString(),
            patientName: booking.fullName,
            reason: booking.reason,
          })
          router.replace('/appointments')
        }}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  screen: { flex: 1, backgroundColor: colours.canvas },
  summary: { paddingHorizontal: 16, paddingTop: 16, fontSize: 15, color: colours.text },
  link: { marginHorizontal: 16, paddingVertical: 12, fontSize: 16, color: colours.accent },
})
TSX

new Date(startsAt).toISOString() turns the clinic's local time into the UTC string the table expects. If the insert throws, part 2's form catches it, keeps what the patient typed and shows its error message above the button, so a failed save is never silent. The phone number and date of birth stay in the form values and are not written to the phone. Part 4 sends them, with the booking, to the clinic's server. Nothing imports src/booking/pending.ts any more; you can delete it.

Check it worked

Check that every screen still bundles with the database code in it. The export builds the web version of the app:

Bash
cd ~/larkfield-app-demo
npx expo export --platform web
grep -rl "larkfield.db" dist > /dev/null && echo "database provider is in the bundle"
grep -rl "Choose a service and a time first" dist > /dev/null && echo "booking screen is in the bundle"

The export ends with Exported: dist, and the last two commands print database provider is in the bundle and booking screen is in the bundle.

Then run the app and try it on a phone or simulator:

Bash
cd ~/larkfield-app-demo
npx expo start

Choose General check-up, tap a time and fill in the form. After you press the button, the Appointments tab opens and shows the booking. Cancel it, confirm, and it leaves the list. Book another one, then close the app completely (swipe it away from the recent apps list) and open it again: the booking is still there. Turn on aeroplane mode and open the tab once more; the list does not need the network.

Troubleshooting

  • no such table: appointments: the database was created before your first migration ran correctly, and user_version already says it is up to date. While you are developing, delete the app's data (on Android, long-press the app icon, then App info, Storage, Clear storage; on iOS, delete the app) or call deleteDatabaseAsync('larkfield.db') from expo-sqlite once. Never do this in a released app: write a new migration instead.
  • The list does not update after a booking: check that options={{ enableChangeListener: true }} is on the SQLiteProvider. Without it, no change events are sent.
  • The database is at version 3, but this app only knows 2: you installed an older build over a newer one. Install the newer build again, or clear the app's data.
  • The details screen says Choose a service and a time first. after you tap a time: the time screen still passes service and time. Check the params change in src/app/(tabs)/book/[serviceId].tsx.
  • Jest fails with Cannot find module 'better-sqlite3': run npm install in ~/larkfield-app-demo again, from the same computer that runs the tests.

Step 8 · Keep part 1's route tests running

Part 1's src/__tests__/routes.test.tsx renders the whole app with renderRouter, so it now goes through the root layout's DatabaseProvider. That provider needs expo-sqlite's native database, which does not exist when Jest runs on your computer, so npm test no longer passes as it did at the end of part 2: the route tests fail on the missing native module, or wait on the "Opening your appointments" message and never find their text.

The fix follows the same rule as the data tests: replace only the native part. Give the route tests a stand-in for expo-sqlite that hands every screen the in-memory database from earlier, with the migrations applied, and lets SQLiteProvider render its children straight away:

Bash
cd ~/larkfield-app-demo
cat > src/db/testing/expo-sqlite-stand-in.ts <<'TS'
// For tests only: replaces expo-sqlite, whose native database does not exist under Jest.
// Screens get an in-memory database with every migration applied, so their SQL runs for real.
import type { ReactNode } from 'react'

import { prepareDatabase } from '../migrations'
import { openMemoryDb } from './memory-db'

const db = openMemoryDb()
void prepareDatabase(db)

export function SQLiteProvider({ children }: { children: ReactNode }) {
  return children
}

export function useSQLiteContext() {
  return db
}

export function addDatabaseChangeListener() {
  return { remove() {} }
}
TS

Then add this line at the very top of src/__tests__/routes.test.tsx, above the import, so the route tests use it:

TSX
jest.mock('expo-sqlite', () => require('../db/testing/expo-sqlite-stand-in'))

Or add it with this command, which stops with an error if the file does not start the way part 1 wrote it:

Bash
cd ~/larkfield-app-demo
node -e "
const fs = require('fs')
const file = 'src/__tests__/routes.test.tsx'
const first = \"import { renderRouter, screen } from 'expo-router/testing-library'\"
const line = \"jest.mock('expo-sqlite', () => require('../db/testing/expo-sqlite-stand-in'))\"
const src = fs.readFileSync(file, 'utf8')
if (!src.startsWith(first)) throw new Error(file + ' does not start with: ' + first)
fs.writeFileSync(file, line + '\\n\\n' + src)
"
head -n 1 src/__tests__/routes.test.tsx

Jest moves jest.mock calls above the imports, so the stand-in is in place before the router loads any screen. The detail route test still opens appointment 42 from part 1's sample data, because the detail screen has not changed. Part 7 replaces this one-file stand-in with a shared one in Jest's setup file that every test uses.

Check it worked

Run every test file in the project:

Bash
cd ~/larkfield-app-demo
npx jest --ci

Jest runs six test suites: part 1's route tests, part 2's phone, schema and form tests, and this part's two database suites. All of them pass, Test Suites: 6 passed, 6 total. If the route tests fail with an error from inside expo-sqlite, the jest.mock line is missing or is not the first line of the file.

Next steps

Leave ~/larkfield-app-demo in place: the next part builds on this database.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.