expo-sqlite を使用すると、WebSQL のような API を通じてクエリできるデータベースにアプリがアクセスできるようになります。 データベースはアプリを再起動しても保持されます。
開発環境(Expo Bare)
- “typescript”: “^5.2.2”
- “expo”: “~49.0.13”,
- “react”: “18.2.0”,
- “react-native”: “0.72.6”,
- “expo-router”: “^2.0.0”,
- “react-native-paper”: “^5.10.6”,
- “expo-sqlite“: “~11.3.3”,
セットアップする
.db 拡張子を認識させる
// metro.config.js
const { getDefaultConfig } = require('expo/metro-config');
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push('db'); // <-- 追加する
module.exports = defaultConfig;
expo-sqlite
パッケージを設置する
npx expo install expo-sqlite npx pod-install
フック(Hooks)を作成する
SQLiteの使用上、SQL Queryを実行する際、コンポネートのレンダリング(re-render)を手動で行う必要がありますので、useForceUpdateフックを作成しておきます。
export function useForceUpdate() {
const [value, setValue] = React.useState(0);
return () => setValue(value + 1);
}
データを処理する(CRUD+)
データベースをオープンする
import * as SQLite from "expo-sqlite";
function openDatabase() {
const db = SQLite.openDatabase("foo.db"); // データベース名(foo.db)は任意
return db;
}
const db = openDatabase()
export default function RootLayout() {
...
CREATE TABLE …
useEffect(() => {
db.transaction((tx) => {
tx.executeSql(
"CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT, done INT, value TEXT);"
);
});
}, []);
INSERT INTO …
SELECT <カラム名> FROM …
const forceUpdate = useForceUpdate();
const addItem = (text) => {
if (text === null || text === "") {
return false;
}
db.transaction(
(tx) => {
tx.executeSql("INSERT INTO items (done, value) values (0, ?)", [text]);
tx.executeSql("SELECT * FROM items", [], (_, { rows }) =>
console.log(JSON.stringify(rows))
);
},
undefined,
forceUpdate
);
};
UPDATE <テーブル名> SET …
const forceUpdate = useForceUpdate();
const updateItem = (id) => {
db.transaction(
(tx) => {
tx.executeSql("UPDATE items SET done = 1 WHERE id = ?;", [id]);
},
undefined,
forceUpdate
);
};
DELETE FROM …
const forceUpdate = useForceUpdate();
const deleteItem = (id) => {
db.transaction(
(tx) => {
tx.executeSql("DELETE FROM items WHERE id = ?;", [id]);
},
undefined,
forceUpdate
);
};
DROP TABLE …
const forceUpdate = useForceUpdate();
const dropTable = (id) => {
db.transaction(
(tx) => {
tx.executeSql("DROP TABLE IF EXISTS items ");
},
undefined,
forceUpdate
);
};
リリースする
※上記の詳細は以下のアプリに実装されています!


コメント