Efficient data logging is important for tracking user activity and performance in mobile apps. In React Native, SQLite is a lightweight database option that runs seamlessly on your device without the need for an external server. This guide shows you how to set up data logging using SQLite in your React Native app.
SQLite is serverless, fast, and built into the device’s file system, making it ideal for local storage and logging tasks in mobile apps.
Install and start react-native-sqlite-storage
:
npm install react-native-sqlite-storage
Initialize the SQLite database.
import SQLite from 'react-native-sqlite-storage';
const db = SQLite.openDatabase({name: 'app_database.db', location: 'default'});
Create a table to store log data such as event type, timestamp, and details.
db.transaction((tx) => {
tx.executeSql(
`CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
event_type TEXT,
details TEXT
);`
);
});
Insert events into a table and log them.
const logEvent = (eventType, details = '') => {
const timestamp = new Date().toISOString();
db.transaction((tx) => {
tx.executeSql(
`INSERT INTO logs (timestamp, event_type, details) VALUES (?, ?, ?);`,
[timestamp, eventType, details]
);
});
};
Get logs with a simple query.
db.transaction((tx) => {
tx.executeSql(
`SELECT * FROM logs ORDER BY timestamp DESC;`,
[],
(tx, results) => console.log('Logs:', results.rows.raw())
);
});
The Gallery section constantly uses SQLite functionality to track user interactions and control thousands of media data. This allows users to interact with the application quickly and effectively. Scrite is the best.