Skip to content

Commit 5bd6cd2

Browse files
committed
docs: update readme
1 parent d8a3e63 commit 5bd6cd2

3 files changed

Lines changed: 117 additions & 124 deletions

File tree

README.md

Lines changed: 82 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,18 @@ Build real-time, collaborative mobile apps that work seamlessly offline and auto
1919
No manual setup required — just access the full [SQLite Sync API](https://github.com/sqliteai/sqlite-sync/blob/main/API.md) directly through the `writeDb` / `readDb` instances.
2020

2121
- 📱 **Native-Only, Ultra-Fast**
22-
Under the hood, we use OP-SQLite — a low-level, JSI-enabled SQLite engine for React Native With OP-SQLite, database operations run at near-native speed on iOS and Android.
22+
Under the hood, we use OP-SQLite — a low-level, JSI-enabled SQLite engine for React Native. With OP-SQLite, database operations run at near-native speed on iOS and Android.
2323

2424
## 📚 Table of Contents
2525

2626
- [Requirements](#-requirements)
2727
- [Installation](#-installation)
2828
- [Quick Start](#-quick-start)
29+
- [Sync Behavior](#-sync-behavior)
2930
- [API Reference](#-api-reference)
3031
- [SQLiteSyncProvider](#sqlitesyncprovider)
3132
- [Contexts](#contexts)
32-
- [SQLiteDbContext](#sqlitedbcontext)
33-
- [SQLiteSyncStatusContext](#sqlitesyncstatuscontext)
34-
- [SQLiteSyncActionsContext](#sqlitesyncactionscontext)
3533
- [Hooks](#hooks)
36-
- [useSqliteDb](#usesqlitedb)
37-
- [useSyncStatus](#usesyncstatus)
38-
- [useSqliteSync](#usesqlitesync)
39-
- [useTriggerSqliteSync](#usetriggersqlitesync)
40-
- [useSqliteSyncQuery](#usesqlitesyncquery)
41-
- [useOnTableUpdate](#useontableupdate)
42-
- [useSqliteExecute](#usesqliteexecute)
43-
- [useSqliteTransaction](#usesqlitetransaction)
44-
- [Types](#types)
4534
- [Error Handling](#-error-handling)
4635
- [Debug Logging](#-debug-logging)
4736
- [Examples](#-examples)
@@ -251,11 +240,17 @@ Synchronization happens automatically in response to meaningful events:
251240
- **App resume from background** → immediate sync (debounced to 5s)
252241
- **Network reconnection** → immediate sync
253242
254-
**Secondary Trigger (Polling Mode):**
243+
**Secondary Triggers:**
244+
245+
_Polling Mode:_
255246
256247
- **Periodic polling while foreground** → interval adapts based on activity
257248
- **No polling when backgrounded**
258249
250+
_Push Mode (Expo only):_
251+
252+
- **Push notification from SQLite Cloud** → immediate sync when changes detected on server
253+
259254
### Adaptive Polling Algorithm
260255
261256
In polling mode, the sync interval intelligently adjusts based on activity:
@@ -306,17 +301,20 @@ Main provider component that enables sync functionality.
306301
307302
#### Props
308303
309-
| Prop | Type | Required | Description |
310-
| ------------------ | ----------------------- | -------- | -------------------------------------------------- |
311-
| `connectionString` | `string` | ✅ | SQLite Cloud connection string |
312-
| `databaseName` | `string` | ✅ | Local database file name |
313-
| `tablesToBeSynced` | `TableConfig[]` | ✅ | Array of tables to sync |
314-
| `syncMode` | `'polling' \| 'push'` | ❌ | Sync mode (default: `'polling'`) |
315-
| `adaptivePolling` | `AdaptivePollingConfig` | ❌ | Adaptive polling configuration (polling mode only) |
316-
| `apiKey` | `string` | \* | API key for authentication |
317-
| `accessToken` | `string` | \* | Access token for RLS authentication |
318-
| `debug` | `boolean` | ❌ | Enable debug logging (default: `false`) |
319-
| `children` | `ReactNode` | ✅ | Child components |
304+
| Prop | Type | Required | Description |
305+
| ------------------------------- | --------------------------- | -------- | ---------------------------------------------------------- |
306+
| `connectionString` | `string` | ✅ | SQLite Cloud connection string |
307+
| `databaseName` | `string` | ✅ | Local database file name |
308+
| `tablesToBeSynced` | `TableConfig[]` | ✅ | Array of tables to sync |
309+
| `apiKey` | `string` | \* | API key for authentication |
310+
| `accessToken` | `string` | \* | Access token for RLS authentication |
311+
| `syncMode` | `'polling' \| 'push'` | ❌ | Sync mode (default: `'polling'`) |
312+
| `adaptivePolling` | `AdaptivePollingConfig` | ❌ | Adaptive polling configuration (polling mode only) |
313+
| `notificationListening` | `'foreground' \| 'always'` | ❌ | When to listen for push notifications (push mode only) |
314+
| `onBeforePushPermissionRequest` | `() => Promise<boolean>` | ❌ | Custom UI before system permission prompt (push mode only) |
315+
| `onDatabaseReady` | `(db: DB) => Promise<void>` | ❌ | Callback after DB opens, before sync init (for migrations) |
316+
| `debug` | `boolean` | ❌ | Enable debug logging (default: `false`) |
317+
| `children` | `ReactNode` | ✅ | Child components |
320318
321319
\* Either `apiKey` or `accessToken` is required
322320
@@ -364,6 +362,63 @@ Uses push notifications from SQLite Cloud:
364362
>
365363
```
366364
365+
#### Background Sync Callback (Push Mode)
366+
367+
When using push mode with `notificationListening: 'always'`, you can register a callback that runs after background sync completes. This is useful for showing local notifications about new data:
368+
369+
```typescript
370+
import { registerBackgroundSyncCallback } from '@sqliteai/sqlite-sync-react-native';
371+
import * as Notifications from 'expo-notifications';
372+
373+
// Register at module level (outside components)
374+
registerBackgroundSyncCallback(async ({ changes, db }) => {
375+
// Find new inserts in your table
376+
const newItems = changes.filter(
377+
(c) => c.table === 'tasks' && c.operation === 'INSERT'
378+
);
379+
380+
if (newItems.length === 0) return;
381+
382+
// Query the synced data
383+
const result = await db.execute(
384+
`SELECT * FROM tasks WHERE rowid IN (${newItems.map((c) => c.rowId).join(',')})`
385+
);
386+
387+
// Show a local notification
388+
await Notifications.scheduleNotificationAsync({
389+
content: {
390+
title: `${newItems.length} new tasks synced`,
391+
body: result.rows?.[0]?.title || 'New data available',
392+
},
393+
trigger: null,
394+
});
395+
});
396+
```
397+
398+
#### Database Migrations with `onDatabaseReady`
399+
400+
Use `onDatabaseReady` to run migrations or other setup after the database opens but before sync initialization:
401+
402+
```typescript
403+
<SQLiteSyncProvider
404+
connectionString="..."
405+
databaseName="myapp.db"
406+
apiKey="..."
407+
tablesToBeSynced={[...]}
408+
onDatabaseReady={async (db) => {
409+
// Check current schema version
410+
const { rows } = await db.execute('PRAGMA user_version');
411+
const version = rows?.[0]?.user_version ?? 0;
412+
413+
// Run migrations
414+
if (version < 1) {
415+
await db.execute('ALTER TABLE tasks ADD COLUMN priority INTEGER DEFAULT 0');
416+
await db.execute('PRAGMA user_version = 1');
417+
}
418+
}}
419+
>
420+
```
421+
367422
#### `AdaptivePollingConfig`
368423

369424
Configuration for adaptive polling behavior (polling mode only).
@@ -1049,7 +1104,8 @@ Enable detailed logging during development:
10491104
10501105
Check out the [examples](./examples) directory for complete working examples:
10511106
1052-
- **[sync-demo](./examples/sync-demo)** - Basic sync demonstration with CRUD operations
1107+
- **[sync-demo-expo](./examples/sync-demo-expo)** - Expo development build with sync demonstration using push notifications
1108+
- **[sync-demo-bare](./examples/sync-demo-bare)** - Bare React Native project with sync demonstration using polling
10531109
10541110
## 🔗 Links
10551111

examples/sync-demo-bare/README.md

Lines changed: 13 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,12 @@ Before running the example, you need to set up a SQLite Cloud database:
3636
4. **Enable OffSync for the table**
3737

3838
- Navigate to **Databases > OffSync** page in the dashboard
39-
- Select \`test_table\` to enable synchronization
39+
- Select `test_table` to enable synchronization
4040
- Learn more about [OffSync configuration](https://docs.sqlitecloud.io/docs/offsync#configuring-offsync)
4141

4242
5. **Get your credentials**
4343
- Navigate to your database's **Configuration** tab
44-
- Copy your **Connection String** (format: \`sqlitecloud://your-host.sqlite.cloud:8860/your-database\`)
44+
- Copy your **Connection String** (format: `sqlitecloud://your-host.sqlite.cloud:8860/your-database`)
4545
- Copy your **API Key**
4646

4747
### 2. Set Up React Native Environment
@@ -50,14 +50,14 @@ Follow the [React Native environment setup guide](https://reactnative.dev/docs/s
5050

5151
### 3. Configure Environment Variables
5252

53-
1. **Create a \`.env\` file**
53+
1. **Create a `.env` file**
5454

5555
```bash
5656
cd examples/sync-demo-bare
5757
cp .env.example .env
5858
```
5959

60-
2. **Fill in your credentials** in the \`.env\` file:
60+
2. **Fill in your credentials** in the `.env` file:
6161

6262
```env
6363
SQLITE_CLOUD_CONNECTION_STRING=sqlitecloud://your-host.sqlite.cloud:8860/your-database
@@ -66,7 +66,7 @@ Follow the [React Native environment setup guide](https://reactnative.dev/docs/s
6666
TABLE_NAME=test_table
6767
```
6868

69-
**Note**: The \`TABLE_NAME\` must match the table name you created in SQLite Cloud and enabled for OffSync.
69+
**Note**: The `TABLE_NAME` must match the table name you created in SQLite Cloud and enabled for OffSync.
7070

7171
### 4. Install Dependencies
7272

@@ -75,64 +75,24 @@ Follow the [React Native environment setup guide](https://reactnative.dev/docs/s
7575
yarn install
7676
```
7777

78-
This will install dependencies for both the library and the example.
79-
80-
### 5. Install iOS Pods (iOS only)
81-
82-
```bash
83-
# From repository root
84-
cd examples/sync-demo-bare/ios
85-
pod install
86-
cd ../../..
87-
```
88-
8978
## Running the Example
9079

91-
You can run the example from either the **repository root** or the **example directory**.
92-
93-
### Option 1: Run from Root (Recommended)
94-
95-
This automatically builds the library and runs the example:
80+
From the repository root:
9681

9782
```bash
98-
# From repository root
9983
yarn bare:ios # Build library + run iOS
10084
yarn bare:android # Build library + run Android
10185
```
10286

103-
### Option 2: Run from Example Directory
104-
105-
If you prefer to run commands from the example directory:
106-
107-
```bash
108-
# From repository root
109-
cd examples/sync-demo-bare
110-
111-
# iOS
112-
yarn ios
113-
114-
# Android
115-
yarn android
116-
```
117-
118-
## Differences from Expo Version
119-
120-
This bare React Native example:
121-
122-
- Uses React Native CLI instead of Expo
123-
- Has direct access to native iOS and Android folders
124-
- Requires manual CocoaPods installation for iOS
125-
- Provides a more traditional React Native development experience
126-
- Ensures the library works correctly without Expo dependencies
127-
12887
## How It Works
12988

130-
The demo app:
89+
The demo app demonstrates:
13190

132-
1. Creates a local SQLite database that syncs with the cloud
133-
2. Allows you to add text entries that are automatically synced
134-
3. Displays sync status and last sync time
135-
4. Auto-reloads data when changes are received
91+
1. **SQLiteSyncProvider** - Creates a local SQLite database that syncs with the cloud
92+
2. **Adaptive polling sync** - Automatically syncs at intelligent intervals
93+
3. **Reactive queries** - Uses `useSqliteSyncQuery` for automatic UI updates
94+
4. **Row-level notifications** - Uses `useOnTableUpdate` for change tracking
95+
5. **Manual sync** - Uses `useTriggerSqliteSync` for on-demand sync
13696

13797
## Try It Out
13898

@@ -143,7 +103,7 @@ The demo app:
143103
- Turn off your internet connection
144104
- Add entries in the app (they'll be saved locally)
145105
- Turn your internet back on
146-
- Watch the sync automatically happen and changes appear in the cloud!
106+
- Watch the sync automatically happen
147107

148108
## Learn More
149109

examples/sync-demo-expo/README.md

Lines changed: 22 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# SQLite Sync React Native - Sync Demo
1+
# SQLite Sync React Native - Expo Demo
22

3-
This is an example Expo app demonstrating the usage of `@sqliteai/sqlite-sync-react-native`.
3+
This is an example **Expo** app demonstrating the usage of `@sqliteai/sqlite-sync-react-native` with push notification sync mode.
44

55
## Setup Instructions
66

@@ -51,7 +51,7 @@ Follow the [React Native environment setup guide](https://reactnative.dev/docs/s
5151
1. **Create a `.env` file**
5252

5353
```bash
54-
cd examples/sync-demo
54+
cd examples/sync-demo-expo
5555
cp .env.example .env
5656
```
5757

@@ -73,61 +73,38 @@ Follow the [React Native environment setup guide](https://reactnative.dev/docs/s
7373
yarn install
7474
```
7575

76-
This will install dependencies for both the library and the example.
77-
7876
## Running the Example
7977

80-
You can run the example from either the **repository root** or the **example directory**.
81-
82-
### Option 1: Run from Root (Recommended)
83-
84-
This automatically builds the library and runs the example:
78+
From the repository root:
8579

8680
```bash
87-
# From repository root
88-
yarn ios # Build library + run iOS
89-
yarn android # Build library + run Android
81+
yarn expo:ios:device # Build library + run iOS
82+
yarn expo:android:device # Build library + run Android
9083
```
9184

92-
### Option 2: Run from Example Directory
93-
94-
If you prefer to run commands from the example directory:
95-
96-
```bash
97-
# From repository root
98-
cd examples/sync-demo
99-
100-
# iOS
101-
yarn ios
102-
103-
# Android
104-
yarn android
105-
```
106-
107-
These commands will:
108-
1. Run `expo prebuild --clean` to generate native folders
109-
2. For iOS: install CocoaPods dependencies
110-
3. Build and launch the app
111-
11285
## How It Works
11386

114-
The demo app:
87+
The demo app demonstrates:
11588

116-
1. Creates a local SQLite database that syncs with the cloud
117-
2. Allows you to add text entries that are automatically synced
118-
3. Displays sync status and last sync time
119-
4. Auto-reloads data when changes are received
89+
1. **SQLiteSyncProvider** - Creates a local SQLite database that syncs with the cloud
90+
2. **Push notification sync** - Uses `expo-notifications` for real-time sync triggers
91+
3. **Reactive queries** - Uses `useSqliteSyncQuery` for automatic UI updates
92+
4. **Row-level notifications** - Uses `useOnTableUpdate` for change tracking
93+
5. **Manual sync** - Uses `useTriggerSqliteSync` for on-demand sync
94+
6. **Background sync callback** - Uses `registerBackgroundSyncCallback` for background notifications
12095

12196
## Try It Out
12297

123-
**Test Real-Time Sync:**
124-
- Open the app on multiple devices or alongside the SQLite Cloud dashboard to see real-time synchronization in action!
98+
**Test Push Notification Sync:**
99+
1. Run the app on a real device (push notifications don't work on simulators)
100+
2. Grant push notification permissions when prompted
101+
3. Add data from the SQLite Cloud dashboard
102+
4. Watch the app sync instantly via push notification
125103

126-
**Test Offline Mode:**
127-
- Turn off your internet connection
128-
- Add entries in the app (they'll be saved locally)
129-
- Turn your internet back on
130-
- Watch the sync automatically happen and changes appear in the cloud!
104+
**Test Permission Denial Fallback:**
105+
1. Deny push notification permissions when prompted
106+
2. The app automatically falls back to polling mode
107+
3. Data still syncs, just on a polling interval instead of instantly
131108

132109
## Learn More
133110

0 commit comments

Comments
 (0)