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

Constellation Diagram of ASK in Detail

A binary bit '1' is assigned a power level of E b \sqrt{E_b}  (or energy E b E_b ), while a binary bit '0' is assigned zero power (or no energy).   Simulator for Binary ASK Constellation Diagram SNR (dB): 15 Run Simulation Noisy Modulated Signal (ASK) Original Modulated Signal (ASK) Energy per bit (Eb) (Tb = bit duration): We know that all periodic signals are power signals. Now we’ll find the energy of ASK for the transmission of binary ‘1’. E b = ∫ 0 Tb (A c .cos(2П.f c .t)) 2 dt = ∫ 0 Tb (A c ) 2 .cos 2 (2П.f c .t) dt Using the identity cos 2 x = (1 + cos(2x))/2: = ∫ 0 Tb ((A c ) 2 /2)(1 + cos(4П.f c .t)) dt ...

Online Simulator for ASK, FSK, and PSK

Try our new Digital Signal Processing Simulator!   Start Simulator for binary ASK Modulation Message Bits (e.g. 1,0,1,0) Carrier Frequency (Hz) Sampling Frequency (Hz) Run Simulation Simulator for binary FSK Modulation Input Bits (e.g. 1,0,1,0) Freq for '1' (Hz) Freq for '0' (Hz) Sampling Rate (Hz) Visualize FSK Signal Simulator for BPSK Modulation ...

UGC NET Electronic Science Previous Year Question Papers

Home / Engineering & Other Exams / UGC NET 2022: Previous Year Question Papers ... UGC-NET (Electronics Science, Subject code: 88) 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 [Sep 2024]  UGC Net Paper 1 With Answer Key Download Pdf [June 2023] with full explanation UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2023] with full explanation UGC Net Electronic Science Question Paper With Answer Key Download Pdf [June 2023] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2022] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [June 2022] UGC Net Electronic Science Question Paper With Answer Key Download Pdf [December 2021] ...

MATLAB Code for Rms Delay Spread

RMS delay spread is crucial when you need to know how much the signal is dispersed in time due to multipath propagation, the spread (variance) around the average. In high-data-rate systems like LTE, 5G, or Wi-Fi, even small time dispersions can cause ISI. RMS delay spread is directly related to the amount of ISI in such systems. RMS Delay Spread [↗] Delay Spread Calculator Enter delays (ns) separated by commas: Enter powers (dB) separated by commas: Calculate   The above calculator Converts Power to Linear Scale: It correctly converts the power values from decibels (dB) to a linear scale. Calculates Mean Delay: It accurately computes the mean excess delay, which is the first moment of the power delay profile. Calculates RMS Delay Spread: It correctly calculates the RMS delay spread, defined as the square root of the second central moment of the power delay profile.   MATLAB Code  clc...

Theoretical vs. simulated BER vs. SNR for ASK, FSK, and PSK

📘 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...

BER vs SNR for M-ary QAM, M-ary PSK, QPSK, BPSK, ...

📘 Overview of BER and SNR 🧮 Online Simulator for BER calculation of m-ary QAM and m-ary PSK 🧮 MATLAB Code for BER calculation of M-ary QAM, M-ary PSK, QPSK, BPSK, ... 📚 Further Reading 📂 View Other Topics on M-ary QAM, M-ary PSK, QPSK ... 🧮 Online Simulator for Constellation Diagram of m-ary QAM 🧮 Online Simulator for Constellation Diagram of m-ary PSK 🧮 MATLAB Code for BER calculation of ASK, FSK, and PSK 🧮 MATLAB Code for BER calculation of Alamouti Scheme 🧮 Different approaches to calculate BER vs SNR What is Bit Error Rate (BER)? The abbreviation BER stands for Bit Error Rate, which indicates how many corrupted bits are received (after the demodulation process) compared to the total number of bits sent in a communication process. BER = (number of bits received in error) / (total number of tran...

MATLAB Code for ASK, FSK, and PSK

📘 Overview & Theory 🧮 MATLAB Code for ASK 🧮 MATLAB Code for FSK 🧮 MATLAB Code for PSK 🧮 Simulator for binary ASK, FSK, and PSK Modulations 📚 Further Reading ASK, FSK & PSK HomePage MATLAB Code MATLAB Code for ASK Modulation and Demodulation % The code is written by SalimWireless.Com % Clear previous data and plots clc; clear all; close all; % Parameters Tb = 1; % Bit duration (s) fc = 10; % Carrier frequency (Hz) N_bits = 10; % Number of bits Fs = 100 * fc; % Sampling frequency (ensure at least 2*fc, more for better representation) Ts = 1/Fs; % Sampling interval samples_per_bit = Fs * Tb; % Number of samples per bit duration % Generate random binary data rng(10); % Set random seed for reproducibility binary_data = randi([0, 1], 1, N_bits); % Generate random binary data (0 or 1) % Initialize arrays for continuous signals t_overall = 0:Ts:(N_bits...

Theoretical BER vs SNR for BPSK

Theoretical Bit Error Rate (BER) vs Signal-to-Noise Ratio (SNR) for BPSK in AWGN Channel Let’s simplify the explanation for the theoretical Bit Error Rate (BER) versus Signal-to-Noise Ratio (SNR) for Binary Phase Shift Keying (BPSK) in an Additive White Gaussian Noise (AWGN) channel. Key Points Fig. 1: Constellation Diagrams of BASK, BFSK, and BPSK [↗] BPSK Modulation Transmits one of two signals: +√Eb or −√Eb , where Eb is the energy per bit. These signals represent binary 0 and 1 . AWGN Channel The channel adds Gaussian noise with zero mean and variance N₀/2 (where N₀ is the noise power spectral density). Receiver Decision The receiver decides if the received signal is closer to +√Eb (for bit 0) or −√Eb (for bit 1) . Bit Error Rat...