SQLite lets your app save and read data on the device. Using expo-sqlite helps you work with SQLite easily in React Native apps.
SQLite with expo-sqlite in React Native
import * as SQLite from 'expo-sqlite'; const db = SQLite.openDatabase('mydb.db'); db.transaction(tx => { tx.executeSql('SQL QUERY', [], (tx, results) => { // handle results }); });
Use openDatabase to create or open a database file.
Use transaction to run SQL commands safely.
const db = SQLite.openDatabase('test.db');db.transaction(tx => {
tx.executeSql('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY NOT NULL, name TEXT);');
});db.transaction(tx => {
tx.executeSql('INSERT INTO items (name) VALUES (?);', ['Apple']);
});db.transaction(tx => {
tx.executeSql('SELECT * FROM items;', [], (tx, results) => {
console.log(results.rows._array);
});
});This app creates a local SQLite database and a table called 'items'. It shows a button to add new items. When you press the button, a new item is saved and the list updates to show all items.
import React, { useEffect, useState } from 'react'; import { View, Text, Button, FlatList } from 'react-native'; import * as SQLite from 'expo-sqlite'; const db = SQLite.openDatabase('mydb.db'); export default function App() { const [items, setItems] = useState([]); const fetchItems = () => { db.transaction(tx => { tx.executeSql('SELECT * FROM items;', [], (tx, results) => { setItems(results.rows._array); }); }); }; const addItem = () => { const newItem = 'Item ' + (items.length + 1); db.transaction(tx => { tx.executeSql('INSERT INTO items (name) VALUES (?);', [newItem], () => { fetchItems(); }); }); }; useEffect(() => { db.transaction(tx => { tx.executeSql( 'CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY NOT NULL, name TEXT);', [], () => fetchItems() ); }); }, []); return ( <View style={{ flex: 1, padding: 20 }}> <Button title="Add Item" onPress={addItem} /> <FlatList data={items} keyExtractor={item => item.id.toString()} renderItem={({ item }) => <Text>{item.name}</Text>} /> </View> ); }
Always run database commands inside transaction for safety.
Use placeholders ? in SQL to avoid errors and injection.
Remember to update your UI state after database changes to show fresh data.
expo-sqlite lets you store data locally in a small database.
Open a database, create tables, insert and query data with SQL commands.
Use React state to show database data in your app interface.
Practice
expo-sqlite in a React Native app?Solution
Step 1: Understand expo-sqlite functionality
expo-sqlite provides a way to store data locally on the device using a SQLite database.Step 2: Compare options with expo-sqlite purpose
Only To store and manage data locally using a small database describes local data storage with a database, which matches expo-sqlite's role.Final Answer:
To store and manage data locally using a small database -> Option AQuick Check:
expo-sqlite = local database storage [OK]
- Confusing expo-sqlite with network data fetching
- Thinking expo-sqlite handles UI styling
- Assuming expo-sqlite manages user login
Solution
Step 1: Recall expo-sqlite database opening method
The correct method to open or create a database isopenDatabase.Step 2: Match method names with options
Only const db = SQLite.openDatabase('mydb.db'); usesopenDatabase, which is the correct syntax.Final Answer:
const db = SQLite.openDatabase('mydb.db'); -> Option DQuick Check:
openDatabase() opens SQLite DB [OK]
- Using createDatabase() which does not exist
- Using connect() or newDatabase() which are invalid
- Missing the correct method name openDatabase()
const db = SQLite.openDatabase('test.db');
db.transaction(tx => {
tx.executeSql('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY NOT NULL, name TEXT);');
tx.executeSql('INSERT INTO items (name) VALUES (?)', ['apple']);
tx.executeSql('SELECT * FROM items;', [], (_, { rows }) => {
console.log(rows._array);
});
});Solution
Step 1: Understand the SQL commands executed
The code creates a table if missing, inserts one row with name 'apple', then selects all rows.Step 2: Analyze the SELECT query result
The SELECT returns one row with id 1 and name 'apple', logged as an array of objects.Final Answer:
[{ id: 1, name: 'apple' }] -> Option BQuick Check:
Inserted row appears in SELECT result [OK]
- Expecting empty array before insertion
- Confusing rows._array with undefined
- Assuming syntax error from correct SQL
db.transaction(tx => {
tx.executeSql('INSERT INTO users (name, age) VALUES (?, ?)', ['John']);
});Solution
Step 1: Check SQL placeholders and values
The SQL has two placeholders (?, ?) but only one value 'John' is provided.Step 2: Identify mismatch causing error
Mismatch between placeholders and values causes an error during execution.Final Answer:
The SQL statement has fewer values than placeholders -> Option AQuick Check:
Placeholders must match values count [OK]
- Ignoring mismatch between placeholders and values
- Assuming table name is wrong without checking
- Thinking executeSql cannot use placeholders
const [items, setItems] = useState([]);
useEffect(() => {
db.transaction(tx => {
tx.executeSql('SELECT * FROM items;', [], (_, { rows }) => {
// What should go here?
});
});
}, []);Solution
Step 1: Understand React state update
To update UI, React state settersetItemsmust be called with new data.Step 2: Identify correct way to update state
Assigning directly toitemsor returning data won't update state; logging only shows data.Final Answer:
setItems(rows._array); -> Option CQuick Check:
Use setItems() to update state and UI [OK]
- Assigning directly to state variable instead of using setter
- Returning data inside executeSql callback
- Only logging data without updating state
Ready to prove it?
Pass the test and this pattern moves unknown
