'Sqlite-expo operations are not altering/fetching data from the database
I'm trying to use SQLite to store some data on my React Native + Expo app. I have created crud-style operations on the database, but when I try to perform any of those operations on the database, I get no errors no modifications and not any data back.
Database Connection
import * as SQLite from 'expo-sqlite';
const db = SQLite.openDatabase('./database.db');
export default db;
Database operation 1 Creating table
import db from '../databaseConection';
db.transaction((tx) => {
tx.executeSql(
`CREATE TABLE IF NOT EXISTS table (id TEXT UNIQUE, value TEXT, dataType TEXT);`,
[],
(_, { rowsAffected }) => {
if (rowsAffected > 0) {
console.log(`DATABASE: Table created.`);
updateTableValues = true;
} else console.log(`DATABASE: Table not created: `);
},
(_, error) => console.log(error)
);
});
When I perform the code above, the database doesn't throw any errors and doesn't create the table, (yes the table that I am trying to create was not already created).
For testing proposes, I created the table using dbeaver and inserted some data just to try to perform some queries.
Database operation 2 Query data
db.transaction((tx) => {
tx.executeSql(
`SELECT * FROM table;`,
(_, { rows }) => console.log(rows._array),
(_, error) => console.log(error)
);
});
Once again, I get no errors and not one single row in the response. I have make sure that the table exists and has data on it.
What exactly I'm doing wrong? and what would be the correct way to access the database?
I'm usign expo: 44.0.0 and expo-sqlite: 10.1.0
Solution 1:[1]
try initializing your database in a function so that you can call it later
export function init() {
const promise = new Promise((resolve, reject) => {
database.transaction((tx) => {
tx.executeSql(
`
CREATE TABLE IF NOT EXISTS table (
id TEXT UNIQUE,
value TEXT,
dataType TEXT
)
`, [],
() => {
console.log("table created")
resolve();
},
(_, err) => {
reject(err);
}
);
});
});
return promise;
}
Then, in App.js
const [isDbInitialized, setIsDbInitialized] = useState(false);
useEffect(() => {
init()
.then(setIsDbInitialized(true))
.catch((err) => console.log(err));
}, []);
if (!isDbInitialized) {
return <Text>Loading...</Text>;
}
return (All your screens in case db is initialized successfully)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Salwa A. Soliman |
