Open In App

What are the options of storing persisting data in a react native app ?

Last Updated : 02 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

When we create React Native apps, there are several ways to store or persist data. Each storage method has its own strong advantage. In this article, we will discuss the all popular ways to persist data in our React Native application.

Before discussing methods of persistent data you should have basic knowledge of JavaScript and React/React Native. You should understand how to use libraries and configuration in your React Native application to persist data.

Prerequisite:

  1. Basic knowledge of JavaScript library
  2. Basic knowledge of React native application

 

Methods of persisting data in React Native:

React Native provides several ways to persist data. Here we discuss the most popular ways. Some methods are inbuilt libraries that you have to install and use and others are external plugins. The following methods are popular for persisting data in React Native.

1. AsyncStorage: It is officially a way to persist data in React Native applications. This is given by the React native in their Documentation. Basically, AsyncStorage functions like a storage class and it gets key-value pairs to persist data as parameters.

But Asyncstorage class is asynchronous; data storage on the device is not permanent and not encrypted, therefore when using this method, you will need to provide your backup and synchronization classes. So that if you’ll be dealing with a large amount of data in your application do not use the AsyncStorage method.

How to use AsyncStorage: Follow the below steps:

Step 1: Import the AsyncStorage library:

This line of code imports AsyncStorage class libraries from React native application package.

import { AsyncStorage } from "react-native";

Step 2: Persist data:

This creates a function that saves your data asynchronously

_storeData = async () => {
    try {
        await AsyncStorage.setItem('name', 'Tom');
    } catch (error) {
        // Error saving data
    }
}

Step 3: Fetch persisted data:

It fetches the data back asynchronously

_retrieveData = async () => {
    try {
        const value = await AsyncStorage.getItem('name');
        if (value !== null) {
            // Our data is fetched successfully
            console.log(value);
        }
    } catch (error) {
        // Error retrieving data
    }
}

2. React Native SQLite 2: This is not a React libraries function, that’s why you may install this plugin externally in your React Native application. This plugin is provided by the WebSQL API to persist data. It uses query operations to persist data into our database.

It supports all operating systems like windows, iOS, and Android. This plugin may be considered as a replacement of the react-native-sqlite-storage library.

How to use React Native SQLite 2: Follow the below steps:

Step 1: Install React Native SQLite 2:

$ npm install react-native-sqlite-2 --save

Step 2: Link to the library dependency:

$ react-native link react-native-sqlite-2

Step 3: Import the library:  

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

Step 4:Open the database file:

const db = SQLite.openDatabase('test.db', '1.0', '', 1);

Step 5: Create a transaction function to execute your SQL statements:

db.transaction(function (txn) {

// Drop the table if it exists
txn.executeSql(‘DROP TABLE IF EXISTS Users’, []);

// Create the table and define the properties of the columns
txn.executeSql(‘CREATE TABLE IF NOT EXISTS Users(user_id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(30))’, []);

// Insert a record
txn.executeSql(‘INSERT INTO Users (name) VALUES (:name)’, [‘tom’]);

// Insert another record
txn.executeSql(‘INSERT INTO Users (name) VALUES (:name)’, [‘jerry’]);

// Select all inserted records, loop over them while printing them on the console.
txn.executeSql(‘SELECT * FROM `users`’, [], function (tx, res) {
for (let i = 0; i < res.rows.length; ++i) {
console.log(‘item:’, res.rows.item(i));
}
});
});

3. Realm: It is specifically designed for mobile devices. It is an object-oriented based database and this makes it up to 10x faster than SQLite. It’s simple to use because it supports relational database systems. It exposes data as an object.

Realm can be joined with server-side data sets to permit consistent synchronization of information disconnected from the cloud/server data set. Realm is a good choice if you’ll be dealing with large data in your application.

How to use Realm: Follow the below steps:

Step 1: Install realm in React Native:

$ npm install realm --save

Step 2: Link to the library dependency:

$ react-native link realm

Step 3: Import the library:

const Realm = require('realm');

 Step 4: Initiate the realm state to null:

constructor(props) {
    super(props);
    this.state = { realm: null };
}

Step 5: Persist on the data:

componentWillMount() {

    // Open a Realm Schema 
    Realm.open({
        schema: [{ name: 'Dog', properties: { name: 'string' } }]
    }).then(realm => {

        // Write a record into the realm schema
        realm.write(() => {
            realm.create('Dog', { name: 'Rex' });
        });

        // Update the realm state
        this.setState({ realm });
    });
}

Step 6: Fetch and render:

render() {
    const info = this.state.realm ? 
        'Number of dogs in this Realm: ' + 
        this.state.realm.objects('Dog').length : 
        'Loading...';
    return (
        <View style={styles.container}></View>
        <Text style={styles.welcome}>
            {info}
        </Text>
        </View >
    );
} 

Step 7: Putting fetch and render together as a component:

// import the library 
const Realm = require('realm');

class RealmDb extends Component {

    //initiate the realm state to null
    constructor(props) {
        super(props);
        this.state = { realm: null };
    }

    // persist data and write it into the realm state 
    // as soon as the component mounts
    componentWillMount() {

        // Open a Realm Schema 
        Realm.open({
            schema: [{ name: 'Dog', properties: { name: 'string' } }]
        }).then(realm => {

            // Write a record into the realm schema
            realm.write(() => {
                realm.create('Dog', { name: 'Rex' });
            });

            // Update the realm state
            this.setState({ realm });
        });

    }

    // render a Text component with the value
    render() {
        const info = this.state.realm ? 
        'Number of dogs in this Realm: ' + 
        this.state.realm.objects('Dog').length : 
        'Loading...';
        return (
            <View style={styles.container}></View>
            <Text style={styles.welcome}>
                {info}
            </Text>
            </View >
        );
    }
}

4. React Native Local MongoDB: MongoDB is a cross-platform, document-oriented server-side database that provides, high performance, availability, and easy scalability. MongoDB works on the concept of Documents.

MongoDB is an open-source, document-oriented server-side database built for scalability and complex applications and Big data. It uses key-value stores and a relational database to store data as objects in JSON documents.

MongoDB allows smooth communication between the server and the app. When you’ll be dealing with large data in your application then It’s the right choice.

How to use MongoDB: Follow the below steps:

Step 1: Install MongoDB in your React Native application:

$ npm install react-native-local-mongodb --save

Step 2: Create a datastore:

var Datastore = require('react-native-local-mongodb'), 
db = new Datastore({ filename: 'asyncStorageKey', autoload: true });

Step 3: Insert into your database:

db.insert([{ a: 5 }, { a: 42 }], function (err, newDocs) {
    // Two documents were inserted in the database
});

Step 4: Find a document:

db.find({ system: 'solar' }, function (err, docs) {
    // docs is an array containing documents Mars, Earth, Jupiter
    // If no document is found, docs is equal to []
});

Step 5: Update a document:

db.update({ planet: 'Jupiter' }, {
    planet: 'Neptune}, {}, function (err, numReplaced) {
    // numReplaced = 1
    // The doc has been replaced 
    // by { _id: 'id3', planet: 'Neptune' }
    // Note that the _id is kept unchanged, 
    // and the document has been replaced
});

Step 6: Remove a document:

db.remove({ _id: 'id2' }, {}, function (err, numRemoved) {
    // numRemoved = 1   
});
Indexing:

db.ensureIndex({ fieldName: 'somefield' }, function (err) {
    // If there was an error, err is not null
});  

Conclusion: In this article, we discussed the all popular ways to persist data in our React Native application. Which data persisting method is used depends on the type and amount of data you’ll be handling.

We have seen four methods of persisting data in React Native, each method having its own advantages. AsyncStorage is dealing with law storage and serialized data while SQLite, Realm, and MongoDB are dealing with large storage data. 

According to the complexity of the app, you can use one of the methods in the above list.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads