How to integrate SQLite with React Native for local storage

SQLite is a lightweight database solution ideal for local storage in mobile applications. This article provides a step-by-step guide for integrating SQLite with React Native.



Why Choose SQLite for Local Storage?

SQLite offers a robust and easy-to-use solution for local storage. Key advantages include:

  • Lightweight: Minimal overhead, making it suitable for mobile apps.
  • Offline Support: Enables apps to function without an internet connection.
  • Structured Data Management: Uses SQL queries for efficient data handling.

Prerequisites for SQLite Integration

Before starting, ensure you have the following:

  • A working React Native environment.
  • Basic knowledge of JavaScript and SQL.
  • Node.js and npm/yarn installed.

Install the SQLite library using the following command:

npm install react-native-sqlite-storage

For iOS, link the library manually:

npx pod-install

Setting Up SQLite

Follow these steps to configure SQLite in your React Native app:

1. Import SQLite

import SQLite from 'react-native-sqlite-storage';

2. Open or Create a Database

const db = SQLite.openDatabase(
    {
        name: 'MyDatabase.db',
        location: 'default',
    },
    () => {
        console.log('Database opened successfully');
    },
    error => {
        console.log('Error opening database:', error);
    }
);

Performing CRUD Operations

1. Create a Table

db.transaction(tx => {
    tx.executeSql(
        `CREATE TABLE IF NOT EXISTS tasks (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT,
            completed BOOLEAN
        );`
    );
});

2. Insert Data

db.transaction(tx => {
    tx.executeSql(
        `INSERT INTO tasks (title, completed) VALUES (?, ?)`,
        ['Sample Task', false]
    );
});

3. Read Data

db.transaction(tx => {
    tx.executeSql(
        `SELECT * FROM tasks`,
        [],
        (tx, results) => {
            let tasks = [];
            for (let i = 0; i < results.rows.length; i++) {
                tasks.push(results.rows.item(i));
            }
            console.log(tasks);
        }
    );
});

4. Update Data

db.transaction(tx => {
    tx.executeSql(
        `UPDATE tasks SET completed = ? WHERE id = ?`,
        [true, 1]
    );
});

5. Delete Data

db.transaction(tx => {
    tx.executeSql(
        `DELETE FROM tasks WHERE id = ?`,
        [1]
    );
});

Best Practices for Using SQLite

  • Always close the database connection when not in use.
  • Use parameterized queries to prevent SQL injection.
  • Regularly back up data for critical applications.

Advanced Techniques

For enhanced functionality, consider the following:

  • Redux Integration: Use Redux to manage application state alongside SQLite for persistent storage.
  • Data Synchronization: Sync offline data with a remote server using REST APIs.


Post a Comment

0 Comments