Skip to main content

How to Build an Offline Mobile App with React Native, Expo, and SQLite


In this article, we will discuss how to create an expense tracker mobile app using React Native, Expo, and a smartphone's local SQLite database. SQLite is similar to MySQL but is designed for mobile and embedded applications. Every smartphone has a local SQLite database that apps can use. However, locating these databases on your device can be tricky because they are stored within the app's sandbox, and each app has its own sandboxed storage.

In this guide, we will focus on an offline expense tracker that stores your expense data in a local SQLite database. For this example, we have named the database my.db. The app stores information such as the expense ID, day, date, expense amount, and any optional comments related to the expense.

Within the my.db database, we have created two tables: users and todos. The users table stores the id, day, date, and expense amount, while the todos table stores the comments. The two tables are linked using a foreign key, allowing the app to display comments associated with specific expenses, if any have been added.


Code for Creating a Database


import * as SQLite from 'expo-sqlite';

const db = SQLite.openDatabase('mydb.db'); 

export const initDB = () => {
  db.transaction(tx => {
    // Enable foreign key constraints
    tx.executeSql('PRAGMA foreign_keys = ON;');

    // Users table
    tx.executeSql(
      `CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        day TEXT,
        date TEXT,
        amount REAL
      );`
    );

    // Todos table (linked to users)
    tx.executeSql(
      `CREATE TABLE IF NOT EXISTS todos (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        user_id INTEGER,
        title TEXT,
        description TEXT,
        FOREIGN KEY(user_id) REFERENCES users(id)
      );`
    );
  });
};

export default db;

See how to render the SQLite data

import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ScrollView, Button } from 'react-native';
import * as SQLite from "expo-sqlite";

let db;
(async () => {
  db = await SQLite.openDatabaseAsync("mydb.db");
})();

const getUsersWithTodos = async (callback) => {
  if (!db) return;

  const users = await db.getAllAsync(`SELECT * FROM users;`);
  const todos = await db.getAllAsync(`SELECT * FROM todos;`);

  const usersWithTodos = users.map(user => ({
    ...user,
    todos: todos.filter(t => t.user_id === user.id),
  }));

  const totalAmount = users.reduce((sum, u) => sum + (u.amount || 0), 0);

  callback({ data: usersWithTodos, totalAmount });
};

const currencySymbols = {
  USD: '$',
  GBP: '£',
  EUR: '€',
  JPY: '¥',
  INR: '₹',
};

const UserList = ({ refreshFlag, currency }) => {
  const [usersData, setUsersData] = useState({ data: [], totalAmount: 0 });

  useEffect(() => {
    getUsersWithTodos(setUsersData);
  }, [refreshFlag]);

  const formatCurrency = (amount) =>
    `${currencySymbols[currency] || ''}${amount.toFixed(2)}`;

  const deleteUser = async (id) => {
    if (!db) return;

    await db.runAsync(`DELETE FROM users WHERE id = ?;`, [id]);
    await db.runAsync(`DELETE FROM todos WHERE user_id = ?;`, [id]);

    getUsersWithTodos(setUsersData);
  };

  return (
    
      Expenses
      
        Total Amount: {formatCurrency(usersData.totalAmount)}
      

      {usersData.data.map(user => (
        
          ID: {user.id}
          Day: {user.day}
          Date: {user.date}
          Amount: {formatCurrency(user.amount)}
          {user.todos.length > 0 ? (
            user.todos.map((t, idx) => (
              Comment: {t.title} - {t.description}
            ))
          ) : (
            No Comment
          )}
          
      ))}
    
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16, backgroundColor: '#fff' },
  title: { fontSize: 22, fontWeight: 'bold', marginBottom: 8 },
  total: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
    color: '#1e3a8a',
  },
  item: {
    backgroundColor: '#f3f4f6',
    padding: 12,
    borderRadius: 8,
    marginBottom: 10,
    borderWidth: 1,
    borderColor: '#d1d5db',
  },
});

export default UserList;
export { getUsersWithTodos, db };
 

How to Render Data from a Local SQLite Database

To retrieve and render data from the local SQLite database (mydb.db), we use simple SQL queries. For example:


const users = await db.getAllAsync(`SELECT * FROM users;`);
const todos = await db.getAllAsync(`SELECT * FROM todos;`);
    

These commands execute SQL SELECT statements to fetch all records from the users and todos tables, respectively.


Visit Github

Further Reading

  1.     

People are good at skipping over material they already know!

View Related Topics to







Contact Us

Name

Email *

Message *

Popular Posts

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...(MATLAB Code + Simulator)

Bit Error Rate (BER) & SNR Guide Analyze communication system performance with our interactive simulators and MATLAB tools. ๐Ÿ“˜ Theory ๐Ÿงฎ Simulators ๐Ÿ’ป MATLAB Code ๐Ÿ“š Resources BER Definition SNR Formula BER Calculator MATLAB Comparison ๐Ÿ“‚ Explore M-ary QAM, PSK, and QPSK Topics ▼ ๐Ÿงฎ Constellation Simulator: M-ary QAM ๐Ÿงฎ Constellation Simulator: M-ary PSK ๐Ÿงฎ BER calculation for ASK, FSK, and PSK ๐Ÿงฎ Approaches to BER vs SNR What is Bit Error Rate (BER)? The BER indicates how many corrupted bits are received compared to the total number of bits sent. It is the primary figure of merit for a...

Online Simulator for ASK, FSK, and PSK

Try our new Digital Signal Processing Simulator!   •   Interactive ASK, FSK, and BPSK tools updated for 2025. Start Now Interactive Modulation Simulators Visualize binary modulation techniques (ASK, FSK, BPSK) in real-time with adjustable carrier and sampling parameters. ๐Ÿ“ก ASK Simulator ๐Ÿ“ถ FSK Simulator ๐ŸŽš️ BPSK Simulator ๐Ÿ“š More Topics ASK Modulator FSK Modulator BPSK Modulator More Topics Simulator for Binary ASK Modulation Digital Message Bits Carrier Freq (Hz) Sampling Rate (...

Constellation Diagrams of ASK, PSK, and FSK (with MATLAB Code + Simulator)

Constellation Diagrams: ASK, FSK, and PSK Comprehensive guide to signal space representation, including interactive simulators and MATLAB implementations. ๐Ÿ“˜ Overview ๐Ÿงฎ Simulator ⚖️ Theory ๐Ÿ“š Resources Definitions Constellation Tool Key Points MATLAB Code ๐Ÿ“‚ Other Topics: M-ary PSK & QAM Diagrams ▼ ๐Ÿงฎ Simulator for M-ary PSK Constellation ๐Ÿงฎ Simulator for M-ary QAM Constellation BASK (Binary ASK) Modulation Transmits one of two signals: 0 or -√Eb, where Eb​ is the energy per bit. These signals represent binary 0 and 1. BFSK (Binary FSK) Modulation Transmits one ...

Time / Frequency Separation for Orthogonality

๐Ÿ“˜ Theory ๐Ÿ“ Derivation ๐Ÿ“Š Examples ๐Ÿงฎ Simulator Try the Interactive BFSK / FM Simulator Visualize modulation and understand concepts faster. Launch BFSK Simulator Launch FM Simulator BFSK Orthogonality Simulator Derivation of Frequency Separation for Orthogonality Step 1: Define BFSK Signals Copy s₁(t) = √(2E b /T) cos(2ฯ€f₁t) Copy s₂(t) = √(2E b /T) cos(2ฯ€f₂t) Defined over: 0 ≤ t ≤ T For orthogonality: Copy ∫₀แต€ s₁(t)s₂(t) dt = 0 Step 2: Remove Constants Copy ∫₀แต€ cos(2ฯ€f₁t) cos(2ฯ€f₂t) dt = 0 Step 3: Use Trigonometric Identity Copy cos A cos B = ½ [ cos(A − B) + cos(A + B) ] Applying identity: Copy ½ ∫₀แต€ [ cos(2ฯ€(f₁ − f₂)t) + cos(2ฯ€(f₁ + f₂)t) ] dt Ste...

Online Simulator for Frequency Modulatiuon

Frequency Modulation Message Frequency (Hz): Generate Message Carrier Frequency (Hz): Generate Carrier Message Signal Amplitude: Carrier Signal Amplitude: Generate Modulated Signal Demodulate Further Reading  Amplitude Modulation Simulator Phase Modulation Simulator  Explore DSP Simulations   Online Signal Processing Simulations Home Page >

UGC NET Electronic Science Previous Year Question Papers

Home / Engineering & Other Exams / UGC NET 2022 PYQ ๐Ÿ“ฅ Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading UGC-NET (Electronics Science, Subject code: 88) Subject_Code : 88; Department : Electronic Science; ๐Ÿ“‚ View All Question Papers UGC Net Electronic Science Question Paper With Answer Key Download Pdf [June 2025] with full explanation UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2024] UGC Net Paper 1 With Answer Key Download Pdf [Sep 2024] with full explanation UGC Net Electronic Science Question Paper With Answer Key Download Pdf [Aug 2024] with full explanation UGC Net Paper 1 With Answer Key Download...

FM Modulation Online Simulator

Frequency Modulation Simulator Message Frequency (fm): Hz Carrier Frequency (fc): Hz Carrier Amplitude (Ac): Modulation Index (ฮฒ): Frequency deviation ฮ”f = ฮฒ × fm Online Signal Processing Simulations Home Page >

Theoretical vs. simulated BER vs. SNR for ASK, FSK, and PSK (MATLAB Code + Simulator)

๐Ÿ“˜ Overview ๐Ÿงฎ Simulator for calculating BER ๐Ÿงฎ MATLAB Codes for calculating theoretical BER ๐Ÿงฎ MATLAB Codes for calculating simulated BER ๐Ÿ“š Further Reading BER vs. SNR denotes how many bits in error are received for a given signal-to-noise ratio, typically measured in dB. Common noise types in wireless systems: 1. Additive White Gaussian Noise (AWGN) 2. Rayleigh Fading AWGN adds random noise; Rayleigh fading attenuates the signal variably. A good SNR helps reduce these effects. Simulator for calculating BER vs SNR for binary ASK, FSK, and PSK Calculate BER for Binary ASK Modulation Enter SNR (dB): Calculate BER Calculate BER for Binary FSK Modulation Enter SNR (dB): Calculate BER Calculate BER for Binary PSK Modulation Enter SNR (dB): Calculate BER BER vs. SNR Curves MATLAB Code for Theoretical BER % The code is written by SalimWireless.Com clc; clear; close all; % SNR va...