This is an example mobile app using Expo with the expo-sqlite driver.
See the Expo installation docs.
Clone this repo and change directory into this folder:
git clone https://github.com/electric-sql/examples
cd examples/expo
Install the dependencies:
yarn
Run in the Android simulator:
yarn android
Run in the iOS simulator:
yarn ios
The application is setup to sync via a local instance of the Electric sync service. See the docs for more information on how to run the backend locally.
The main code to look at is in ./src/Example.tsx
.
export const ElectrifiedExample = () => {
const [db, setDb] = useState<ElectrifiedDatabase>();
useEffect(() => {
const init = async () => {
const original = SQLite.openDatabase('example.db');
const db = await electrify(original, config)
setDb(db)
}
init();
}, []);
if (db === null) {
return null
}
return (
<ElectricProvider db={db}>
<Example />
</ElectricProvider>
);
};
This opens an electrified database client and passes it to the application using the React Context API. Components can then use the useElectric
and useElectricQuery
to access the database client and bind reactive queries to the component state.
const ExampleComponent = () => {
const {results, error} = useElectricQuery('SELECT value FROM items', []);
const db = useElectric() as ElectrifiedDatabase;
if (error !== undefined) {
return (
<View>
<Text style={styles.item}>Error: {`${error}`}</Text>
</View>
);
}
if (results === undefined) {
return null;
}
const addItem = () => {
db.transaction(tx => {
tx.executeSql('INSERT INTO items VALUES(?)', [uuidv4()]);
});
};
const clearItems = async () => {
db.transaction(tx => {
tx.executeSql('DELETE FROM items where true', undefined);
});
};
return (
<View>
{results.map((item, index) => (
<Text key={index} style={styles.item}>
Item: {item.value}
</Text>
))}
<Pressable style={styles.button} onPress={addItem}>
<Text style={styles.text}>Add</Text>
</Pressable>
<Pressable style={styles.button} onPress={clearItems}>
<Text style={styles.text}>Clear</Text>
</Pressable>
</View>
);
};
See the documentation and community guidelines. If you need help let us know on Discord.