React Native Async Await in react-native-sqlite-storage
You need to wrap it in a Promise, then resolve the result when sql execution is done.
for example
async () => { return new Promise((resolve, reject) => { db.transaction(tx => { tx.executeSql('SELECT * FROM users;', [], (tx, results) => { const { rows } = results; let users = []; for (let i = 0; i < rows.length; i++) { users.push({ ...rows.item(i), }); } resolve(users); }); }); });}
let SQLite = require('react-native-sqlite-storage');const DB = SQLite.openDatabase({name:'test.db',createFromLocation:'~sqlitedb.db'});class Database{ db; constructor(db){ this.db =db; } executeSql = (sql,params=[])=>new Promise((resolve , reject)=>{ this.db.transaction((trans)=>{ trans.executeSql(sql,params,(db,results)=>{ resolve(results); }, (error)=>{ reject(error); }); }); });}export default (new Database(DB));
use
import Database from 'database'; try { results = await DB.excuteSql("SQL",['params']); } catch(e) { }
The following worked for me:
import { openDatabase } from 'react-native-sqlite-storage'const db = openDatabase({ name: 'app.db', location: 'default',})export default function App() { useEffect(() => { db.then((db) => { db.transaction((tx) => { tx.executeSql('SELECT this from that', []) }) }) /* Rest of the component... */}
openDatabase
returns a Promise, on resolving which we get the actual db
on which we can run db.transaction()
.
You could use the async/await syntax too, but that would be a lot of encapsulation, and so .then()
is always cleaner.
This is different from the "expo-sqlite" package, because
db = openDatabase('app.db')
does not return a Promise there. Instead, you can rundb.transaction()
directly.