Using SQLite with React Native

Learn via video courses
Topics Covered

Overview

React Native has become a go-to framework for developing mobile applications that work seamlessly across multiple platforms. When it comes to storing and managing data in these applications, developers often look for a reliable and efficient solution. This is where SQLite shines. SQLite is a lightweight and powerful embedded relational database engine that provides an excellent data storage option for React Native projects.

Introduction

In this article, we will learn how to integrate SQLite into your React Native project. We will explore the benefits of using SQLite as a data storage solution and explain how it can enhance the functionality and performance of your React Native apps. Whether you need to store user preferences, manage complex data structures, or build offline-capable apps, SQLite offers the flexibility and efficiency required for seamless data management.

Prerequisites

  • A fundamental understanding of React and React Native
  • Knowledge and experience working with TypeScript

Getting Started

In this tutorial, we will develop a task management application with various features. These include a Done button that removes completed tasks, an Add ToDo button for adding new items, and the implementation of two useState hooks. The useState hooks serve the purpose of maintaining the to-do list and tracking newly added tasks. The main component of our application, called App, will handle user interactions such as adding and deleting tasks from the list.

Additionally, we will be using a separate component, referred to as the Dumb component, to display individual to-do list items. It is important to note that throughout this tutorial, we will be utilizing functional components and use several newly introduced hook APIs for effective state management.

Setting Up React Native and TypeScript

To create a new React Native project using TypeScript, follow the below steps:

Step - 1: Install React Native CLI

Ensure that you have React Native CLI installed globally on your system. You can use npm to install it by executing the following command:

Step - 2: Create a new project

Open your terminal and navigate to the desired directory where you want to create the new React Native project. Use the following command to generate a new project:

Step - 3: Start the development server

To start the development server, execute the following command within the project directory:

Step - 4: Run the application

Open a new terminal window, navigate to the project directory, and run the appropriate command to build and run the app on an emulator or connected device:

For iOS:

For Android:

Introducing SQLite

To utilize SQLite in our application, we will introduce the react-native-sqlite-storage library, which enables seamless integration with SQLite.

Run the following command to install the SQLite package in your React native project.

NPM users:

Yarn users:

Install React Native Packages

For React Native versions 0.60 and higher, the standard procedure involves running the below command to install the necessary dependencies.

iOS

Unlike previous versions, there is no need to perform the linking step in React Native 0.60 and above. If your React Native version is 0.59 or below, you have two installation options for React Native packages, depending on whether you are utilizing CocoaPods.

With CocoaPods:

To use the necessary dependencies in your project when using CocoaPods, follow these steps:

  1. Open your podfile and include the following code:

  2. Save the changes to your podfile.

  3. Run either pod install or pod update to install or update the required pods, respectively.

Without CocoaPods:

If you are not using CocoaPods, the alternative approach is to make use of a react-native link. In the event of encountering any errors, it becomes necessary to access the project through Xcode and manually include the required dependencies. For further information and specifics, kindly consult the documentation provided by the library.

Android

If you want to utilize the SQLite available on the device in React Native 0.60 and above, there are no additional steps required. However, if you prefer to use the bundled SQLite library that includes support for FTS5, you can follow these instructions:

Add the following code to your react-native.config.js file:

For users with React Native 0.59 and below version:

Here are the steps to follow:

Step - 1 - Update Gradle Settings (located under Gradle Settings in Project Panel)

Update the android/settings.gradle file as follows:

Step - 2 - Update app module Gradle Build script (located under Gradle Settings in Project Panel)

Update the android/app/build.gradle file as follows:

Step - 3 - Register React Package

In your MainActivity.java file, add the following code:

Alternatively, if you are using a newer version of React Native (0.18+), you can use the following approach:

Implement a Datastore Service

To implement a datastore service, we can create a separate file called "db-service.ts" where all the database operations will be defined. Firstly, we need to create a method for establishing a database connection. If TypeScript is being used, installing @types/react-native-sqlite-storage is necessary to utilize the included types. However, for JavaScript users, there is no need to install this library.

Below is the code for the database connection method:

If the table does not exist at the start of the application, we need to create one. The following method can be added:

To handle promise-based APIs in the library, the following code should be added to the "db-service.ts" file:

Using the DB Service

Now, let's explore how to use the db service in the "App.tsx" file by following these four steps:

  • Update the ToDoItem and Appcomponents to utilize the newToDoItem` types.
  • Load data from SQLite.
  • Save data to the database.
  • Update deleted items in the database.

Loading Data

For loading data, the useEffect and useCallback hooks will be utilized:

This loadDataCallback function loads data from a database and initializes the state of the todos in a todo application. It uses the loadDataCallback function inside a useEffect hook to asynchronously fetch to-do items from the database.

  • If there are stored todo items, they are set as the state of todos.
  • Otherwise, the initial to-do items are saved to the database and set as the state. Any errors that occur are logged into the console.

Adding an Item

To add a to-do item,

  1. The addTodo function checks if the newTodo value, after removing leading and trailing whitespace, is empty. If it is empty, the function returns early.

  2. If the newTodo value is not empty, a try-catch block is used.

  3. Inside the try block:

    • A new array of todos is created by spreading the existing todos array and adding a new todo object.
    • The new todo object has an id that is determined by finding the maximum id among existing todos and incrementing it by 1, and a value taken from the newTodo variable.
    • The setTodos function is used to update the todos state with the new array of todos.
    • The getDBConnection function is called to establish a database connection asynchronously, and the resulting db object is stored.
    • The saveTodoItems function is called to save the new todos array to the database using the db object.
    • The setNewTodo function is used to clear the newTodo value by setting it to an empty string.
  4. If an error occurs in the try block, it is caught in the catch block, and the error is logged to the console.

Deleting an Item

For deleting a to-do item, the following code should be used:

  • deleteItem is an asynchronous function that takes an id as a parameter.
  • It first establishes a connection to the database by calling the getDBConnection function.
  • deleteItem then calls the deleteTodoItem function, passing the database connection (db) and the item's id to delete. This function deletes the item from the database.
  • It removes the item from the todos array using the splice method, specifying the index (id) and the number of elements to remove (1).
  • It updates the state of the todos array by calling setTodos with a new array created using the spread operator [...todos].

Conclusion

  • React Native SQLite Storage is a powerful library for implementing local data storage in React Native applications.
  • It provides a reliable and efficient solution for managing SQLite databases within the app.
  • The library offers a simple API and supports both JavaScript and TypeScript , making it accessible to a wide range of developers.
  • By utilizing React Native SQLite Storage, developers can leverage the power of SQL queries to perform various database operations.
  • The library allows for efficient data retrieval, insertion, modification, and deletion, enhancing the overall performance of the application.
  • React Native SQLite Storage also supports transactions, enabling developers to execute multiple database operations as a single atomic unit.
  • With its promise-based API, developers can handle asynchronous operations and ensure smooth execution of database actions.
  • The library's compatibility with both iOS and Android platforms makes it a versatile choice for cross-platform development.
  • Overall, React Native SQLite Storage simplifies local data management, provides a reliable storage solution, and contributes to the performance optimization of React Native applications.