Getting started with SQLite in React-Native

Sambhav Jain
codeburst
Published in
4 min readSep 10, 2020

--

Photo by AltumCode on Unsplash

React Native apps come with a simple user interface, code reusability, and allows for the production of stable apps. With React-Native being one of the most popular and ideal frameworks for creating cross-platform mobile applications, the vast majority of the developers and engineers depend on the structure of the framework to deliver high-performing local applications. Because of this, it’s often challenging for developers to choose the right technology stack (including the appropriate database for React Native). In this article we will be discussing SQLite as a local database for React-Native, and work on how to pre-populate data into the database so as to use it in the application.

The word “lite” in SQLite describes it as being a lightweight library based database which requires minimal setup. SQLite can be coordinated with a versatile application, allowing us to get to the database in an easy, straightforward manner. It’s also helpful to note that SQLite was designed to provide local storage to mobile apps.

The two main benefits of using SQLite database are:

  1. It’s ACID-compliant (an acronym for atomicity, consistency, isolation, and durability)
  2. Its offline persistence (which means that it works even when the device is offline)

Creating a database

First, we need to create a database and store some data in it. https://sqliteonline.com/ can help in creating a SQLite database.

Create a new table and use the command- CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
….
);

For example-

CREATE TABLE Users(Title varchar(20),Age number); 

Now we need to insert values to this table structure:

INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

For example:

INSERT INTO Users(Title,Age)
VALUES ("Rohit" , 42);

Now your database is ready and you can download the user.db that you have created. For now, store the file in a temporary location.

Integrating the database with react-native

Step 1: After setting up your react native environment install the SQLite package

npm install react-native-sqlite-storagereact-native link

Step 2:

For iOS:

open ./ios/podfilepod 'react-native-sqlite-storage', :path => '../node_modules/react-native-sqlite-storage'cd ./ios && pod install

For Android:

  1. Open and modify android/settings.gradle file as follows:
rootProject.name = 'react_native_sqlite_storage_exercise'
...
include ':react-native-sqlite-storage'
project(':react-native-sqlite-storage').projectDir = new
File(rootProject.projectDir, '../node_modules/react-native-sqlite- storage/src/android')
...
include ':app'

2. Modify android/app/build.gradle file as follows:

...   
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"]) implementation"com.android.support:appcompatv7:${rootProject.ext.supportLibVersion}"
implementation "com.facebook.react:react-native:+"
...
implementation project(':react-native-sqlite-storage') \
}
...

3. Open and modify MainApplication.java file as below:

...   
import org.pgsqlite.SQLitePluginPackage;
...
public class MainApplication extends Application implements ReactApplication {
...
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
...
new SQLitePluginPackage(),
...
new MainReactPackage()
);
}
}

Step 3: Adding the database file to the correct location

For iOS:

Create ios/[project name]/www folder and copy the database on it.

For Android:

Create www folder in the main project directory and copy the database on it.

Step 4-

Create a constructor and add these lines of code:

The constructor consists of four parts:

  1. The state — which is initially declared as an empty array (this will later be populated with data from the database).
  2. SQLite is imported and openDatabase function is called where the argument it takes is the name of the database and the location of the database.
  3. The success callback function ( which is called if there are no errors).
  4. The error callback function ( which is executed if there is an error).

Step 5-

Now we have to add the success and the fail call back functions:

In the success function, we declare a function db.transaction wherein the first argument we run the SQL query Select * from table_name (this selects all the rows in the SQL database). These rows are stored in a variable called “results”. Now we have to loop through each row of the “results” so that we can store data row by row in the array, thus we use the for loop. Now, after all the rows are pushed to the array, we use setState to update the state value.

In the fail function definition, we console.error the error so that debugging can be easier

Step 6-

We create a render function and display the contents of the table in a scrollable view:

We use Scrollview to make a scrollable view of the list of all items we stored in the database. Now, since the rows are stored as an array of objects in the userList variable, we have to map through each element of the array and print the title and the age of the person.

Conclusion

That’s it! In just six simple steps we have the basic setup of an SQLite database that is rendering its data to the front-end using React-Native. As discussed earlier, React-Native can be an incredibly helpful tool for developers and engineers, but knowing which technology stack is right for the task at hand can be a complicated process. I hope that this article has helped you work through this issue, and to evaluate whether SQLite can act as a worthy local database option for your next project! Thanks for reading and feel free to leave questions or feedback in the comments section.

Click here to view the complete source code.

--

--