mirror of
https://github.com/expo/examples.git
synced 2026-11-15 13:18:12 -10:00
313 lines
6.9 KiB
TypeScript
313 lines
6.9 KiB
TypeScript
import { useState, useEffect, useCallback } from 'react';
|
|
import {
|
|
Button,
|
|
ScrollView,
|
|
StatusBar,
|
|
StyleSheet,
|
|
Switch,
|
|
Text,
|
|
TextInput,
|
|
TouchableOpacity,
|
|
View,
|
|
} from 'react-native';
|
|
import {
|
|
SQLiteProvider,
|
|
useSQLiteContext,
|
|
type SQLiteDatabase,
|
|
} from 'expo-sqlite';
|
|
|
|
/**
|
|
* The Item type represents a single item in database.
|
|
*/
|
|
interface ItemEntity {
|
|
id: number;
|
|
done: boolean;
|
|
value: string;
|
|
}
|
|
|
|
const libSQLOptions = {
|
|
url: process.env.EXPO_PUBLIC_LIBSQL_URL,
|
|
authToken: process.env.EXPO_PUBLIC_LIBSQL_AUTH_TOKEN,
|
|
};
|
|
|
|
//#region Components
|
|
|
|
export default function App() {
|
|
return (
|
|
<SQLiteProvider
|
|
databaseName="libsql.db"
|
|
onInit={migrateDbIfNeeded}
|
|
options={{ libSQLOptions }}
|
|
>
|
|
<Main />
|
|
<StatusBar barStyle="dark-content" />
|
|
</SQLiteProvider>
|
|
);
|
|
}
|
|
|
|
function Main() {
|
|
const db = useSQLiteContext();
|
|
const [text, setText] = useState('');
|
|
const [todoItems, setTodoItems] = useState<ItemEntity[]>([]);
|
|
const [doneItems, setDoneItems] = useState<ItemEntity[]>([]);
|
|
const [enablePollingSync, setEnablePollingSync] = useState(false);
|
|
|
|
const refetchItems = useCallback(() => {
|
|
async function refetch() {
|
|
await db.withTransactionAsync(async () => {
|
|
setTodoItems(
|
|
await db.getAllAsync<ItemEntity>(
|
|
'SELECT * FROM items WHERE done = ?',
|
|
false
|
|
)
|
|
);
|
|
setDoneItems(
|
|
await db.getAllAsync<ItemEntity>(
|
|
'SELECT * FROM items WHERE done = ?',
|
|
true
|
|
)
|
|
);
|
|
});
|
|
}
|
|
refetch();
|
|
}, [db]);
|
|
|
|
const sync = useCallback(
|
|
(refetch: boolean) => {
|
|
db.syncLibSQL();
|
|
if (refetch) {
|
|
refetchItems();
|
|
}
|
|
},
|
|
[db]
|
|
);
|
|
|
|
useEffect(() => {
|
|
refetchItems();
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (enablePollingSync) {
|
|
const intervalId = setInterval(() => {
|
|
sync(true /* refetch */);
|
|
}, 2000);
|
|
return () => {
|
|
clearInterval(intervalId);
|
|
};
|
|
}
|
|
}, [enablePollingSync]);
|
|
|
|
return (
|
|
<View style={styles.container}>
|
|
<Text style={styles.heading}>libSQL Example</Text>
|
|
|
|
<View style={styles.controlContainer}>
|
|
<View style={styles.controlRow}>
|
|
<Text>Manual sync</Text>
|
|
<Button
|
|
title="Sync"
|
|
onPress={() => {
|
|
sync(true /* refetch */);
|
|
}}
|
|
/>
|
|
</View>
|
|
<View style={styles.controlRow}>
|
|
<Text>Auto sync for every 2 seconds</Text>
|
|
<Switch
|
|
onValueChange={(value) => {
|
|
setEnablePollingSync(value);
|
|
}}
|
|
value={enablePollingSync}
|
|
/>
|
|
</View>
|
|
</View>
|
|
|
|
<View style={styles.flexRow}>
|
|
<TextInput
|
|
onChangeText={(text) => setText(text)}
|
|
onSubmitEditing={async () => {
|
|
await addItemAsync(db, text);
|
|
await refetchItems();
|
|
setText('');
|
|
}}
|
|
placeholder="what do you need to do?"
|
|
style={styles.input}
|
|
value={text}
|
|
/>
|
|
</View>
|
|
|
|
<ScrollView style={styles.listArea}>
|
|
<View style={styles.sectionContainer}>
|
|
<Text style={styles.sectionHeading}>Todo</Text>
|
|
{todoItems.map((item) => (
|
|
<Item
|
|
key={item.id}
|
|
item={item}
|
|
onPressItem={async (id) => {
|
|
await updateItemAsDoneAsync(db, id);
|
|
await refetchItems();
|
|
}}
|
|
/>
|
|
))}
|
|
</View>
|
|
<View style={styles.sectionContainer}>
|
|
<Text style={styles.sectionHeading}>Completed</Text>
|
|
{doneItems.map((item) => (
|
|
<Item
|
|
key={item.id}
|
|
item={item}
|
|
onPressItem={async (id) => {
|
|
await deleteItemAsync(db, id);
|
|
await refetchItems();
|
|
}}
|
|
/>
|
|
))}
|
|
</View>
|
|
</ScrollView>
|
|
</View>
|
|
);
|
|
}
|
|
|
|
function Item({
|
|
item,
|
|
onPressItem,
|
|
}: {
|
|
item: ItemEntity;
|
|
onPressItem: (id) => void | Promise<void>;
|
|
}) {
|
|
const { id, done, value } = item;
|
|
return (
|
|
<TouchableOpacity
|
|
onPress={() => onPressItem && onPressItem(id)}
|
|
style={[styles.item, done && styles.itemDone]}
|
|
>
|
|
<Text style={[styles.itemText, done && styles.itemTextDone]}>
|
|
{value}
|
|
</Text>
|
|
</TouchableOpacity>
|
|
);
|
|
}
|
|
|
|
//#endregion
|
|
|
|
//#region Database Operations
|
|
|
|
async function addItemAsync(db: SQLiteDatabase, text: string): Promise<void> {
|
|
if (text !== '') {
|
|
await db.runAsync(
|
|
'INSERT INTO items (done, value) VALUES (?, ?);',
|
|
false,
|
|
text
|
|
);
|
|
}
|
|
}
|
|
|
|
async function updateItemAsDoneAsync(
|
|
db: SQLiteDatabase,
|
|
id: number
|
|
): Promise<void> {
|
|
await db.runAsync('UPDATE items SET done = ? WHERE id = ?;', true, id);
|
|
}
|
|
|
|
async function deleteItemAsync(db: SQLiteDatabase, id: number): Promise<void> {
|
|
await db.runAsync('DELETE FROM items WHERE id = ?;', id);
|
|
}
|
|
|
|
async function migrateDbIfNeeded(db: SQLiteDatabase) {
|
|
// Always sync libSQL first to prevent conflicts between local and remote databases
|
|
await db.syncLibSQL();
|
|
|
|
const DATABASE_VERSION = 1;
|
|
let { user_version: currentDbVersion } = await db.getFirstAsync<{
|
|
user_version: number;
|
|
}>('PRAGMA user_version');
|
|
if (currentDbVersion >= DATABASE_VERSION) {
|
|
return;
|
|
}
|
|
if (currentDbVersion === 0) {
|
|
// libSQL does not support WAL mode
|
|
// await db.execAsync(`PRAGMA journal_mode = 'wal';`);
|
|
await db.execAsync(
|
|
`CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY NOT NULL, done INT, value TEXT);`
|
|
);
|
|
currentDbVersion = 1;
|
|
}
|
|
// if (currentDbVersion === 1) {
|
|
// Add more migrations
|
|
// }
|
|
await db.execAsync(`PRAGMA user_version = ${DATABASE_VERSION}`);
|
|
}
|
|
|
|
//#endregion
|
|
|
|
//#region Styles
|
|
|
|
const styles = StyleSheet.create({
|
|
container: {
|
|
backgroundColor: '#fff',
|
|
flex: 1,
|
|
paddingTop: 64,
|
|
},
|
|
heading: {
|
|
fontSize: 20,
|
|
fontWeight: 'bold',
|
|
textAlign: 'center',
|
|
},
|
|
flexRow: {
|
|
flexDirection: 'row',
|
|
},
|
|
controlContainer: {
|
|
alignItems: 'center',
|
|
flexDirection: 'column',
|
|
justifyContent: 'center',
|
|
marginVertical: 8,
|
|
},
|
|
controlRow: {
|
|
alignSelf: 'stretch',
|
|
justifyContent: 'space-between',
|
|
alignItems: 'center',
|
|
flexDirection: 'row',
|
|
marginHorizontal: 64,
|
|
paddingVertical: 4,
|
|
},
|
|
input: {
|
|
borderColor: '#4630eb',
|
|
borderRadius: 4,
|
|
borderWidth: 1,
|
|
flex: 1,
|
|
height: 48,
|
|
margin: 16,
|
|
padding: 8,
|
|
},
|
|
listArea: {
|
|
backgroundColor: '#f0f0f0',
|
|
flex: 1,
|
|
paddingTop: 16,
|
|
},
|
|
sectionContainer: {
|
|
marginBottom: 16,
|
|
marginHorizontal: 16,
|
|
},
|
|
sectionHeading: {
|
|
fontSize: 18,
|
|
marginBottom: 8,
|
|
},
|
|
item: {
|
|
backgroundColor: '#fff',
|
|
borderColor: '#000',
|
|
borderWidth: 1,
|
|
padding: 8,
|
|
},
|
|
itemDone: {
|
|
backgroundColor: '#1c9963',
|
|
},
|
|
itemText: {
|
|
color: '#000',
|
|
},
|
|
itemTextDone: {
|
|
color: '#fff',
|
|
},
|
|
});
|
|
|
|
//#endregion
|