# Expo

import { Code, Steps, Tabs, TabItem } from '@astrojs/starlight/components'
import { makeCreate, versionNpmSuffix } from '../../../data/data.ts'
import { MIN_NODE_VERSION } from '@local/shared'
import babelConfigCode from '../../../../../examples/expo-todomvc-sync-cf/babel.config.js?raw'
import metroConfigCode from '../../../../../examples/expo-todomvc-sync-cf/metro.config.js?raw'






export const CODE = {
  babelConfig: babelConfigCode,
  metroConfig: metroConfigCode,
}

{/* We're adjusting the package to use the dev version on the dev branch */}
export const manualInstallDepsStr = [
  '@livestore/devtools-expo' + versionNpmSuffix,
  '@livestore/adapter-expo' + versionNpmSuffix,
  '@livestore/livestore' + versionNpmSuffix,
  '@livestore/react' + versionNpmSuffix,
  '@livestore/sync-cf/client' + versionNpmSuffix,
  '@livestore/peer-deps' + versionNpmSuffix,
  'expo-sqlite',
].join(' ')

### Prerequisites

- Recommended: Bun 1.2 or higher
- Node.js {MIN_NODE_VERSION} or higher

To use [LiveStore](/) with [Expo](https://docs.expo.dev/), ensure your project has the [New Architecture](https://docs.expo.dev/guides/new-architecture/) enabled. This is required for transactional state updates.

### Option A: Quick start

For a quick start we recommend using our template app following the steps below.

For existing projects see [Existing project setup](#existing-project-setup).

<Steps>

1.  **Set up project from template**

    <Tabs syncKey="package-manager">
      <TabItem label="bun">
        <Code code={makeCreate('expo-todomvc-sync-cf', 'bunx')} lang="sh" />
      </TabItem>
      <TabItem label="pnpm">
        <Code code={makeCreate('expo-todomvc-sync-cf', 'pnpm dlx')} lang="sh" />
      </TabItem>
      <TabItem label="npm">
        <Code code={makeCreate('expo-todomvc-sync-cf', 'npx')} lang="sh" />
      </TabItem>
      <TabItem label="yarn">
        <Code code={makeCreate('expo-todomvc-sync-cf', 'yarn dlx')} lang="sh" />
      </TabItem>
    </Tabs>

    Replace `livestore-app` with your desired app name.

2.  **Install dependencies**

    It's strongly recommended to use `bun` or `pnpm` for the simplest and most reliable dependency setup (see [note on package management](/misc/package-management) for more details).

    <Tabs syncKey="package-manager">
      <TabItem label="bun">
        ```bash
        bun install
        ```
      </TabItem>
      <TabItem label="pnpm">
        ```bash
        pnpm install --node-linker=hoisted
        ```

        Make sure to use `--node-linker=hoisted` when installing dependencies in your project or add it to your `.npmrc` file.
        ```
        # .npmrc
        nodeLinker=hoisted
        ```

        Hopefully Expo will also support non-hoisted setups in the future.
      </TabItem>
      <TabItem label="npm">
        ```bash
        npm install
        ```
      </TabItem>
      <TabItem label="yarn">
        When using `yarn`, make sure you're using Yarn 4 or higher with the `node-modules` linker.

        ```bash
        yarn set version stable
        yarn config set nodeLinker node-modules
        yarn install
        ```
      </TabItem>
    </Tabs>

    Pro tip: You can use [direnv](https://direnv.net/) to manage environment variables.

3.  **Run the app**

    <Tabs syncKey="package-manager">
      <TabItem label="bun">
        <Code code="bun start" lang="sh" />
      </TabItem>
      <TabItem label="pnpm">
        <Code code="pnpm start" lang="sh" />
      </TabItem>
      <TabItem label="npm">
        <Code code="npm run start" lang="sh" />
      </TabItem>
      <TabItem label="yarn">
        <Code code="yarn start" lang="sh" />
      </TabItem>
    </Tabs>

    In a new terminal, start the Cloudflare Worker (for the sync backend):

    <Tabs syncKey="package-manager">
      <TabItem label="bun">
        <Code code="bun wrangler:dev" lang="sh" />
      </TabItem>
      <TabItem label="pnpm">
        <Code code="pnpm wrangler:dev" lang="sh" />
      </TabItem>
      <TabItem label="npm">
        <Code code="npm run wrangler:dev" lang="sh" />
      </TabItem>
      <TabItem label="yarn">
        <Code code="yarn wrangler:dev" lang="sh" />
      </TabItem>
    </Tabs>
</Steps>

### Option B: Existing project setup \{#existing-project-setup\}

<Steps>

1.  **Install dependencies**

    <Tabs syncKey="package-manager">
      <TabItem label="bun">
        <Code code={'bun install ' + manualInstallDepsStr} lang="sh" />
      </TabItem>
      <TabItem label="pnpm">
        <Code code={'pnpm install ' + manualInstallDepsStr} lang="sh" />
      </TabItem>
      <TabItem label="npm">
        <Code code={'npm install ' + manualInstallDepsStr} lang="sh" />
      </TabItem>
      <TabItem label="yarn">
        <Code code={'yarn add ' + manualInstallDepsStr} lang="sh" />
      </TabItem>
    </Tabs>

2.  **Add Vite meta plugin to babel config file**

    LiveStore Devtools uses Vite. This plugin emulates Vite's `import.meta.env` functionality.

    <Tabs syncKey="package-manager">
      <TabItem label="bun">
        <Code code="bun add -d babel-plugin-transform-vite-meta-env" lang="sh" />
      </TabItem>
      <TabItem label="pnpm">
        <Code code="pnpm add -D babel-plugin-transform-vite-meta-env" lang="sh" />
      </TabItem>
      <TabItem label="yarn">
        <Code code="yarn add -D babel-plugin-transform-vite-meta-env" lang="sh" />
      </TabItem>
      <TabItem label="npm">
        <Code code="npm install --save-dev babel-plugin-transform-vite-meta-env" lang="sh" />
      </TabItem>
    </Tabs>

    In your `babel.config.js` file, add the plugin as follows:

    <Code code={CODE.babelConfig} lang="js" title="babel.config.js" />

3.  **Update Metro config**

    Add the following code to your `metro.config.js` file:

    <Code code={CODE.metroConfig} lang="js" title="metro.config.js" />

</Steps>

## Define your schema

Create a file named `schema.ts` inside the `src/livestore` folder. This file defines your LiveStore schema consisting of your app's event definitions (describing how data changes), derived state (i.e. SQLite tables), and materializers (how state is derived from events).

Here's an example schema:


## `getting-started/expo/livestore/schema.ts`

```ts filename="getting-started/expo/livestore/schema.ts"
import { Events, makeSchema, Schema, SessionIdSymbol, State } from '@livestore/livestore'

export const tables = {
  todos: State.SQLite.table({
    name: 'todos',
    columns: {
      id: State.SQLite.text({ primaryKey: true }),
      text: State.SQLite.text({ default: '' }),
      completed: State.SQLite.boolean({ default: false }),
      deletedAt: State.SQLite.integer({ nullable: true, schema: Schema.DateFromNumber }),
    },
  }),
  uiState: State.SQLite.clientDocument({
    name: 'uiState',
    schema: Schema.Struct({ newTodoText: Schema.String, filter: Schema.Literal('all', 'active', 'completed') }),
    default: { id: SessionIdSymbol, value: { newTodoText: '', filter: 'all' } },
  }),
}

export const events = {
  todoCreated: Events.synced({
    name: 'v1.TodoCreated',
    schema: Schema.Struct({ id: Schema.String, text: Schema.String }),
  }),
  todoCompleted: Events.synced({
    name: 'v1.TodoCompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoUncompleted: Events.synced({
    name: 'v1.TodoUncompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoDeleted: Events.synced({
    name: 'v1.TodoDeleted',
    schema: Schema.Struct({ id: Schema.String, deletedAt: Schema.Date }),
  }),
  todoClearedCompleted: Events.synced({
    name: 'v1.TodoClearedCompleted',
    schema: Schema.Struct({ deletedAt: Schema.Date }),
  }),
  uiStateSet: tables.uiState.set,
}

const materializers = State.SQLite.materializers(events, {
  'v1.TodoCreated': ({ id, text }) => tables.todos.insert({ id, text, completed: false }),
  'v1.TodoCompleted': ({ id }) => tables.todos.update({ completed: true }).where({ id }),
  'v1.TodoUncompleted': ({ id }) => tables.todos.update({ completed: false }).where({ id }),
  'v1.TodoDeleted': ({ id, deletedAt }) => tables.todos.update({ deletedAt }).where({ id }),
  'v1.TodoClearedCompleted': ({ deletedAt }) => tables.todos.update({ deletedAt }).where({ completed: true }),
})

const state = State.SQLite.makeState({ tables, materializers })

export const schema = makeSchema({ events, state })
```

## Configure the store

Create a `store.ts` file in the `src/livestore` folder. This file configures the store adapter and exports a custom hook that components will use to access the store.

The `useStore()` hook accepts store configuration options (schema, adapter, store ID) and returns a store instance. It suspends while the store is loading, so make sure to use a `Suspense` boundary to handle the loading state.


## `getting-started/expo/livestore/store.ts`

```ts filename="getting-started/expo/livestore/store.ts"
import { unstable_batchedUpdates as batchUpdates } from 'react-native'

import { makePersistedAdapter } from '@livestore/adapter-expo'
import { useStore } from '@livestore/react'
import { makeWsSync } from '@livestore/sync-cf/client'

import { events, schema, tables } from './schema.ts'

const syncUrl = 'https://example.org/sync'

const adapter = makePersistedAdapter({
  sync: { backend: makeWsSync({ url: syncUrl }) },
})

export const useAppStore = () =>
  useStore({
    storeId: 'expo-todomvc',
    schema,
    adapter,
    batchUpdates,
    boot: (store) => {
      if (store.query(tables.todos.count()) === 0) {
        store.commit(events.todoCreated({ id: crypto.randomUUID(), text: 'Make coffee' }))
      }
    },
  })
```

### `getting-started/expo/livestore/schema.ts`

```ts filename="getting-started/expo/livestore/schema.ts"
import { Events, makeSchema, Schema, SessionIdSymbol, State } from '@livestore/livestore'

export const tables = {
  todos: State.SQLite.table({
    name: 'todos',
    columns: {
      id: State.SQLite.text({ primaryKey: true }),
      text: State.SQLite.text({ default: '' }),
      completed: State.SQLite.boolean({ default: false }),
      deletedAt: State.SQLite.integer({ nullable: true, schema: Schema.DateFromNumber }),
    },
  }),
  uiState: State.SQLite.clientDocument({
    name: 'uiState',
    schema: Schema.Struct({ newTodoText: Schema.String, filter: Schema.Literal('all', 'active', 'completed') }),
    default: { id: SessionIdSymbol, value: { newTodoText: '', filter: 'all' } },
  }),
}

export const events = {
  todoCreated: Events.synced({
    name: 'v1.TodoCreated',
    schema: Schema.Struct({ id: Schema.String, text: Schema.String }),
  }),
  todoCompleted: Events.synced({
    name: 'v1.TodoCompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoUncompleted: Events.synced({
    name: 'v1.TodoUncompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoDeleted: Events.synced({
    name: 'v1.TodoDeleted',
    schema: Schema.Struct({ id: Schema.String, deletedAt: Schema.Date }),
  }),
  todoClearedCompleted: Events.synced({
    name: 'v1.TodoClearedCompleted',
    schema: Schema.Struct({ deletedAt: Schema.Date }),
  }),
  uiStateSet: tables.uiState.set,
}

const materializers = State.SQLite.materializers(events, {
  'v1.TodoCreated': ({ id, text }) => tables.todos.insert({ id, text, completed: false }),
  'v1.TodoCompleted': ({ id }) => tables.todos.update({ completed: true }).where({ id }),
  'v1.TodoUncompleted': ({ id }) => tables.todos.update({ completed: false }).where({ id }),
  'v1.TodoDeleted': ({ id, deletedAt }) => tables.todos.update({ deletedAt }).where({ id }),
  'v1.TodoClearedCompleted': ({ deletedAt }) => tables.todos.update({ deletedAt }).where({ completed: true }),
})

const state = State.SQLite.makeState({ tables, materializers })

export const schema = makeSchema({ events, state })
```

## Set up the store registry

To enable store management throughout your app, create a `StoreRegistry` and provide it with a `<StoreRegistryProvider>`. The registry manages store instance lifecycles (loading, caching, disposal).

Wrap the provider in a `Suspense` boundary to handle the loading state for when the store is loading.


## `getting-started/expo/Root.tsx`

```tsx filename="getting-started/expo/Root.tsx"
import { StatusBar } from 'expo-status-bar'
import { type FC, Suspense, useState } from 'react'
import { SafeAreaView, Text, View } from 'react-native'

/* oxlint-disable react/style-prop-object */
import { StoreRegistry } from '@livestore/livestore'
import { StoreRegistryProvider } from '@livestore/react'

import { ListTodos } from './components/ListTodos.tsx'
import { NewTodo } from './components/NewTodo.tsx'

const suspenseFallback = <Text>Loading LiveStore...</Text>
const appContentStyle = { flex: 1, gap: 24, padding: 24 }
const safeAreaStyle = { flex: 1 }

const AppContent: FC = () => (
  <View style={appContentStyle}>
    <NewTodo />
    <ListTodos />
  </View>
)

export const Root: FC = () => {
  const [storeRegistry] = useState(() => new StoreRegistry())

  return (
    <SafeAreaView style={safeAreaStyle}>
      <Suspense fallback={suspenseFallback}>
        <StoreRegistryProvider storeRegistry={storeRegistry}>
          <AppContent />
        </StoreRegistryProvider>
      </Suspense>
      <StatusBar style="auto" />
    </SafeAreaView>
  )
}
```

### `getting-started/expo/components/ListTodos.tsx`

```tsx filename="getting-started/expo/components/ListTodos.tsx"
import { type FC, useCallback } from 'react'
import type { TextStyle, ViewStyle } from 'react-native'
import { Button, ScrollView, Text, View } from 'react-native'

import { visibleTodos$ } from '../livestore/queries.ts'
import { events, type tables } from '../livestore/schema.ts'
import { useAppStore } from '../livestore/store.ts'

const listContainerStyle = { flex: 1, gap: 16 } satisfies ViewStyle
const listContentContainerStyle = { gap: 12 } satisfies ViewStyle
const todoContainerStyle = {
  borderRadius: 12,
  borderColor: '#d4d4d8',
  borderWidth: 1,
  padding: 16,
  gap: 8,
} satisfies ViewStyle
const todoTitleStyle = { fontSize: 16, fontWeight: '600' } satisfies TextStyle
const todoActionRowStyle = { flexDirection: 'row', gap: 12 } satisfies ViewStyle

export const ListTodos: FC = () => {
  const store = useAppStore()
  const todos = store.useQuery(visibleTodos$)

  const toggleTodo = useCallback(
    ({ id, completed }: typeof tables.todos.Type) => {
      store.commit(completed === true ? events.todoUncompleted({ id }) : events.todoCompleted({ id }))
    },
    [store],
  )

  const clearCompleted = useCallback(() => {
    store.commit(events.todoClearedCompleted({ deletedAt: new Date() }))
  }, [store])

  return (
    <View style={listContainerStyle}>
      <ScrollView contentContainerStyle={listContentContainerStyle}>
        {todos.map((todo) => (
          <TodoItem key={todo.id} todo={todo} onToggle={toggleTodo} />
        ))}
      </ScrollView>
      <Button title="Clear completed" onPress={clearCompleted} />
    </View>
  )
}

const TodoItem: FC<{
  todo: typeof tables.todos.Type
  onToggle: (todo: typeof tables.todos.Type) => void
}> = ({ todo, onToggle }) => {
  const store = useAppStore()
  const onTogglePress = useCallback(() => onToggle(todo), [onToggle, todo])
  const onDeletePress = useCallback(() => {
    store.commit(events.todoDeleted({ id: todo.id, deletedAt: new Date() }))
  }, [store, todo.id])

  return (
    <View style={todoContainerStyle}>
      <Text style={todoTitleStyle}>{todo.text}</Text>
      <Text>{todo.completed === true ? 'Completed' : 'Pending'}</Text>
      <View style={todoActionRowStyle}>
        <Button title={todo.completed === true ? 'Mark pending' : 'Mark done'} onPress={onTogglePress} />
        <Button title="Delete" onPress={onDeletePress} />
      </View>
    </View>
  )
}
```

### `getting-started/expo/components/NewTodo.tsx`

```tsx filename="getting-started/expo/components/NewTodo.tsx"
import { type FC, useCallback } from 'react'
import { Button, TextInput, View } from 'react-native'

import { uiState$ } from '../livestore/queries.ts'
import { events } from '../livestore/schema.ts'
import { useAppStore } from '../livestore/store.ts'

const formContainerStyle = { gap: 12 }

export const NewTodo: FC = () => {
  const store = useAppStore()
  const { newTodoText } = store.useQuery(uiState$)

  const updateText = useCallback(
    (text: string) => {
      store.commit(events.uiStateSet({ newTodoText: text }))
    },
    [store],
  )
  const createTodo = useCallback(() => {
    store.commit(
      events.todoCreated({ id: crypto.randomUUID(), text: newTodoText }),
      events.uiStateSet({ newTodoText: '' }),
    )
  }, [newTodoText, store])

  const addSampleTodos = useCallback(() => {
    const todos = Array.from({ length: 5 }, (_, index) => ({
      id: crypto.randomUUID(),
      text: `Todo ${index + 1}`,
    }))
    store.commit(...todos.map((todo) => events.todoCreated(todo)))
  }, [store])

  return (
    <View style={formContainerStyle}>
      <TextInput value={newTodoText} onChangeText={updateText} placeholder="What needs to be done?" />
      <Button title="Add todo" onPress={createTodo} />
      <Button title="Add sample todos" onPress={addSampleTodos} />
    </View>
  )
}
```

### `getting-started/expo/livestore/queries.ts`

```ts filename="getting-started/expo/livestore/queries.ts"
import { queryDb } from '@livestore/livestore'

import { tables } from './schema.ts'

export const uiState$ = queryDb(tables.uiState.get(), { label: 'uiState' })

export const visibleTodos$ = queryDb(
  (get) => {
    const { filter } = get(uiState$)

    return tables.todos.where({
      deletedAt: null,
      completed: filter === 'all' ? undefined : filter === 'completed',
    })
  },
  { label: 'visibleTodos' },
)
```

### `getting-started/expo/livestore/schema.ts`

```ts filename="getting-started/expo/livestore/schema.ts"
import { Events, makeSchema, Schema, SessionIdSymbol, State } from '@livestore/livestore'

export const tables = {
  todos: State.SQLite.table({
    name: 'todos',
    columns: {
      id: State.SQLite.text({ primaryKey: true }),
      text: State.SQLite.text({ default: '' }),
      completed: State.SQLite.boolean({ default: false }),
      deletedAt: State.SQLite.integer({ nullable: true, schema: Schema.DateFromNumber }),
    },
  }),
  uiState: State.SQLite.clientDocument({
    name: 'uiState',
    schema: Schema.Struct({ newTodoText: Schema.String, filter: Schema.Literal('all', 'active', 'completed') }),
    default: { id: SessionIdSymbol, value: { newTodoText: '', filter: 'all' } },
  }),
}

export const events = {
  todoCreated: Events.synced({
    name: 'v1.TodoCreated',
    schema: Schema.Struct({ id: Schema.String, text: Schema.String }),
  }),
  todoCompleted: Events.synced({
    name: 'v1.TodoCompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoUncompleted: Events.synced({
    name: 'v1.TodoUncompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoDeleted: Events.synced({
    name: 'v1.TodoDeleted',
    schema: Schema.Struct({ id: Schema.String, deletedAt: Schema.Date }),
  }),
  todoClearedCompleted: Events.synced({
    name: 'v1.TodoClearedCompleted',
    schema: Schema.Struct({ deletedAt: Schema.Date }),
  }),
  uiStateSet: tables.uiState.set,
}

const materializers = State.SQLite.materializers(events, {
  'v1.TodoCreated': ({ id, text }) => tables.todos.insert({ id, text, completed: false }),
  'v1.TodoCompleted': ({ id }) => tables.todos.update({ completed: true }).where({ id }),
  'v1.TodoUncompleted': ({ id }) => tables.todos.update({ completed: false }).where({ id }),
  'v1.TodoDeleted': ({ id, deletedAt }) => tables.todos.update({ deletedAt }).where({ id }),
  'v1.TodoClearedCompleted': ({ deletedAt }) => tables.todos.update({ deletedAt }).where({ completed: true }),
})

const state = State.SQLite.makeState({ tables, materializers })

export const schema = makeSchema({ events, state })
```

### `getting-started/expo/livestore/store.ts`

```ts filename="getting-started/expo/livestore/store.ts"
import { unstable_batchedUpdates as batchUpdates } from 'react-native'

import { makePersistedAdapter } from '@livestore/adapter-expo'
import { useStore } from '@livestore/react'
import { makeWsSync } from '@livestore/sync-cf/client'

import { events, schema, tables } from './schema.ts'

const syncUrl = 'https://example.org/sync'

const adapter = makePersistedAdapter({
  sync: { backend: makeWsSync({ url: syncUrl }) },
})

export const useAppStore = () =>
  useStore({
    storeId: 'expo-todomvc',
    schema,
    adapter,
    batchUpdates,
    boot: (store) => {
      if (store.query(tables.todos.count()) === 0) {
        store.commit(events.todoCreated({ id: crypto.randomUUID(), text: 'Make coffee' }))
      }
    },
  })
```

## Commit events

After setting up the registry, use the `useAppStore()` hook from any component to access the store and commit events.


## `getting-started/expo/components/NewTodo.tsx`

```tsx filename="getting-started/expo/components/NewTodo.tsx"
import { type FC, useCallback } from 'react'
import { Button, TextInput, View } from 'react-native'

import { uiState$ } from '../livestore/queries.ts'
import { events } from '../livestore/schema.ts'
import { useAppStore } from '../livestore/store.ts'

const formContainerStyle = { gap: 12 }

export const NewTodo: FC = () => {
  const store = useAppStore()
  const { newTodoText } = store.useQuery(uiState$)

  const updateText = useCallback(
    (text: string) => {
      store.commit(events.uiStateSet({ newTodoText: text }))
    },
    [store],
  )
  const createTodo = useCallback(() => {
    store.commit(
      events.todoCreated({ id: crypto.randomUUID(), text: newTodoText }),
      events.uiStateSet({ newTodoText: '' }),
    )
  }, [newTodoText, store])

  const addSampleTodos = useCallback(() => {
    const todos = Array.from({ length: 5 }, (_, index) => ({
      id: crypto.randomUUID(),
      text: `Todo ${index + 1}`,
    }))
    store.commit(...todos.map((todo) => events.todoCreated(todo)))
  }, [store])

  return (
    <View style={formContainerStyle}>
      <TextInput value={newTodoText} onChangeText={updateText} placeholder="What needs to be done?" />
      <Button title="Add todo" onPress={createTodo} />
      <Button title="Add sample todos" onPress={addSampleTodos} />
    </View>
  )
}
```

### `getting-started/expo/livestore/queries.ts`

```ts filename="getting-started/expo/livestore/queries.ts"
import { queryDb } from '@livestore/livestore'

import { tables } from './schema.ts'

export const uiState$ = queryDb(tables.uiState.get(), { label: 'uiState' })

export const visibleTodos$ = queryDb(
  (get) => {
    const { filter } = get(uiState$)

    return tables.todos.where({
      deletedAt: null,
      completed: filter === 'all' ? undefined : filter === 'completed',
    })
  },
  { label: 'visibleTodos' },
)
```

### `getting-started/expo/livestore/schema.ts`

```ts filename="getting-started/expo/livestore/schema.ts"
import { Events, makeSchema, Schema, SessionIdSymbol, State } from '@livestore/livestore'

export const tables = {
  todos: State.SQLite.table({
    name: 'todos',
    columns: {
      id: State.SQLite.text({ primaryKey: true }),
      text: State.SQLite.text({ default: '' }),
      completed: State.SQLite.boolean({ default: false }),
      deletedAt: State.SQLite.integer({ nullable: true, schema: Schema.DateFromNumber }),
    },
  }),
  uiState: State.SQLite.clientDocument({
    name: 'uiState',
    schema: Schema.Struct({ newTodoText: Schema.String, filter: Schema.Literal('all', 'active', 'completed') }),
    default: { id: SessionIdSymbol, value: { newTodoText: '', filter: 'all' } },
  }),
}

export const events = {
  todoCreated: Events.synced({
    name: 'v1.TodoCreated',
    schema: Schema.Struct({ id: Schema.String, text: Schema.String }),
  }),
  todoCompleted: Events.synced({
    name: 'v1.TodoCompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoUncompleted: Events.synced({
    name: 'v1.TodoUncompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoDeleted: Events.synced({
    name: 'v1.TodoDeleted',
    schema: Schema.Struct({ id: Schema.String, deletedAt: Schema.Date }),
  }),
  todoClearedCompleted: Events.synced({
    name: 'v1.TodoClearedCompleted',
    schema: Schema.Struct({ deletedAt: Schema.Date }),
  }),
  uiStateSet: tables.uiState.set,
}

const materializers = State.SQLite.materializers(events, {
  'v1.TodoCreated': ({ id, text }) => tables.todos.insert({ id, text, completed: false }),
  'v1.TodoCompleted': ({ id }) => tables.todos.update({ completed: true }).where({ id }),
  'v1.TodoUncompleted': ({ id }) => tables.todos.update({ completed: false }).where({ id }),
  'v1.TodoDeleted': ({ id, deletedAt }) => tables.todos.update({ deletedAt }).where({ id }),
  'v1.TodoClearedCompleted': ({ deletedAt }) => tables.todos.update({ deletedAt }).where({ completed: true }),
})

const state = State.SQLite.makeState({ tables, materializers })

export const schema = makeSchema({ events, state })
```

### `getting-started/expo/livestore/store.ts`

```ts filename="getting-started/expo/livestore/store.ts"
import { unstable_batchedUpdates as batchUpdates } from 'react-native'

import { makePersistedAdapter } from '@livestore/adapter-expo'
import { useStore } from '@livestore/react'
import { makeWsSync } from '@livestore/sync-cf/client'

import { events, schema, tables } from './schema.ts'

const syncUrl = 'https://example.org/sync'

const adapter = makePersistedAdapter({
  sync: { backend: makeWsSync({ url: syncUrl }) },
})

export const useAppStore = () =>
  useStore({
    storeId: 'expo-todomvc',
    schema,
    adapter,
    batchUpdates,
    boot: (store) => {
      if (store.query(tables.todos.count()) === 0) {
        store.commit(events.todoCreated({ id: crypto.randomUUID(), text: 'Make coffee' }))
      }
    },
  })
```

## Queries

To retrieve data from the database, define a query using `queryDb` from `@livestore/livestore`, then execute it with `store.useQuery()`.

Consider abstracting queries into a separate file to keep your code organized, though you can also define them directly within components if preferred.


## `getting-started/expo/components/ListTodos.tsx`

```tsx filename="getting-started/expo/components/ListTodos.tsx"
import { type FC, useCallback } from 'react'
import type { TextStyle, ViewStyle } from 'react-native'
import { Button, ScrollView, Text, View } from 'react-native'

import { visibleTodos$ } from '../livestore/queries.ts'
import { events, type tables } from '../livestore/schema.ts'
import { useAppStore } from '../livestore/store.ts'

const listContainerStyle = { flex: 1, gap: 16 } satisfies ViewStyle
const listContentContainerStyle = { gap: 12 } satisfies ViewStyle
const todoContainerStyle = {
  borderRadius: 12,
  borderColor: '#d4d4d8',
  borderWidth: 1,
  padding: 16,
  gap: 8,
} satisfies ViewStyle
const todoTitleStyle = { fontSize: 16, fontWeight: '600' } satisfies TextStyle
const todoActionRowStyle = { flexDirection: 'row', gap: 12 } satisfies ViewStyle

export const ListTodos: FC = () => {
  const store = useAppStore()
  const todos = store.useQuery(visibleTodos$)

  const toggleTodo = useCallback(
    ({ id, completed }: typeof tables.todos.Type) => {
      store.commit(completed === true ? events.todoUncompleted({ id }) : events.todoCompleted({ id }))
    },
    [store],
  )

  const clearCompleted = useCallback(() => {
    store.commit(events.todoClearedCompleted({ deletedAt: new Date() }))
  }, [store])

  return (
    <View style={listContainerStyle}>
      <ScrollView contentContainerStyle={listContentContainerStyle}>
        {todos.map((todo) => (
          <TodoItem key={todo.id} todo={todo} onToggle={toggleTodo} />
        ))}
      </ScrollView>
      <Button title="Clear completed" onPress={clearCompleted} />
    </View>
  )
}

const TodoItem: FC<{
  todo: typeof tables.todos.Type
  onToggle: (todo: typeof tables.todos.Type) => void
}> = ({ todo, onToggle }) => {
  const store = useAppStore()
  const onTogglePress = useCallback(() => onToggle(todo), [onToggle, todo])
  const onDeletePress = useCallback(() => {
    store.commit(events.todoDeleted({ id: todo.id, deletedAt: new Date() }))
  }, [store, todo.id])

  return (
    <View style={todoContainerStyle}>
      <Text style={todoTitleStyle}>{todo.text}</Text>
      <Text>{todo.completed === true ? 'Completed' : 'Pending'}</Text>
      <View style={todoActionRowStyle}>
        <Button title={todo.completed === true ? 'Mark pending' : 'Mark done'} onPress={onTogglePress} />
        <Button title="Delete" onPress={onDeletePress} />
      </View>
    </View>
  )
}
```

### `getting-started/expo/livestore/queries.ts`

```ts filename="getting-started/expo/livestore/queries.ts"
import { queryDb } from '@livestore/livestore'

import { tables } from './schema.ts'

export const uiState$ = queryDb(tables.uiState.get(), { label: 'uiState' })

export const visibleTodos$ = queryDb(
  (get) => {
    const { filter } = get(uiState$)

    return tables.todos.where({
      deletedAt: null,
      completed: filter === 'all' ? undefined : filter === 'completed',
    })
  },
  { label: 'visibleTodos' },
)
```

### `getting-started/expo/livestore/schema.ts`

```ts filename="getting-started/expo/livestore/schema.ts"
import { Events, makeSchema, Schema, SessionIdSymbol, State } from '@livestore/livestore'

export const tables = {
  todos: State.SQLite.table({
    name: 'todos',
    columns: {
      id: State.SQLite.text({ primaryKey: true }),
      text: State.SQLite.text({ default: '' }),
      completed: State.SQLite.boolean({ default: false }),
      deletedAt: State.SQLite.integer({ nullable: true, schema: Schema.DateFromNumber }),
    },
  }),
  uiState: State.SQLite.clientDocument({
    name: 'uiState',
    schema: Schema.Struct({ newTodoText: Schema.String, filter: Schema.Literal('all', 'active', 'completed') }),
    default: { id: SessionIdSymbol, value: { newTodoText: '', filter: 'all' } },
  }),
}

export const events = {
  todoCreated: Events.synced({
    name: 'v1.TodoCreated',
    schema: Schema.Struct({ id: Schema.String, text: Schema.String }),
  }),
  todoCompleted: Events.synced({
    name: 'v1.TodoCompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoUncompleted: Events.synced({
    name: 'v1.TodoUncompleted',
    schema: Schema.Struct({ id: Schema.String }),
  }),
  todoDeleted: Events.synced({
    name: 'v1.TodoDeleted',
    schema: Schema.Struct({ id: Schema.String, deletedAt: Schema.Date }),
  }),
  todoClearedCompleted: Events.synced({
    name: 'v1.TodoClearedCompleted',
    schema: Schema.Struct({ deletedAt: Schema.Date }),
  }),
  uiStateSet: tables.uiState.set,
}

const materializers = State.SQLite.materializers(events, {
  'v1.TodoCreated': ({ id, text }) => tables.todos.insert({ id, text, completed: false }),
  'v1.TodoCompleted': ({ id }) => tables.todos.update({ completed: true }).where({ id }),
  'v1.TodoUncompleted': ({ id }) => tables.todos.update({ completed: false }).where({ id }),
  'v1.TodoDeleted': ({ id, deletedAt }) => tables.todos.update({ deletedAt }).where({ id }),
  'v1.TodoClearedCompleted': ({ deletedAt }) => tables.todos.update({ deletedAt }).where({ completed: true }),
})

const state = State.SQLite.makeState({ tables, materializers })

export const schema = makeSchema({ events, state })
```

### `getting-started/expo/livestore/store.ts`

```ts filename="getting-started/expo/livestore/store.ts"
import { unstable_batchedUpdates as batchUpdates } from 'react-native'

import { makePersistedAdapter } from '@livestore/adapter-expo'
import { useStore } from '@livestore/react'
import { makeWsSync } from '@livestore/sync-cf/client'

import { events, schema, tables } from './schema.ts'

const syncUrl = 'https://example.org/sync'

const adapter = makePersistedAdapter({
  sync: { backend: makeWsSync({ url: syncUrl }) },
})

export const useAppStore = () =>
  useStore({
    storeId: 'expo-todomvc',
    schema,
    adapter,
    batchUpdates,
    boot: (store) => {
      if (store.query(tables.todos.count()) === 0) {
        store.commit(events.todoCreated({ id: crypto.randomUUID(), text: 'Make coffee' }))
      }
    },
  })
```

## Devtools

To open the devtools, run the app and from your terminal press `shift + m`, then select LiveStore Devtools and press `Enter`.

![Expo Terminal Screenshot](../../../assets/devtools-terminal-expo.png)

This will open the devtools in a new tab in your default browser.

![Devtools Browser Screenshot](../../../assets/devtools-browser-view.png)

Use the devtools to inspect the state of your LiveStore database, execute events, track performance, and more.

## Database location

### With Expo Go

To open the database in Finder, run the following command in your terminal:

```bash
open $(find $(xcrun simctl get_app_container booted host.exp.Exponent data) -path "*/Documents/ExponentExperienceData/*livestore-expo*" -print -quit)/SQLite
```

### With development builds

For development builds, the app SQLite database is stored in the app's Library directory.

Example:
`/Users/<USERNAME>/Library/Developer/CoreSimulator/Devices/<DEVICE_ID>/data/Containers/Data/Application/<APP_ID>/Documents/SQLite/app.db`

To open the database in Finder, run the following command in your terminal:

```bash
open $(xcrun simctl get_app_container booted [APP_BUNDLE_ID] data)/Documents/SQLite
```

Replace `[APP_BUNDLE_ID]` with your app's bundle ID. e.g. `dev.livestore.livestore-expo`.

## Further notes

- LiveStore doesn't yet support Expo Web (see [#130](https://github.com/livestorejs/livestore/issues/130))