RxDB With React Native
A real-time database for JavaScript applications using RxDB
As we continue to rely more and more on technology in our daily lives, the demand for innovative solutions that seamlessly integrate with our digital experiences has never been greater. From mobile apps to web applications and everything in between, the need for reliable, efficient, and scalable databases has become increasingly apparent.
RxDB offers modules for real-time replication with any database-compliant endpoint, as well as with specific GraphQL endpoints, in order to replicate data between your clients and server.
What is RxDB?
RxDB is short for Reactive Database, a NoSQL database for JavaScript applications like websites, mobile apps, electro-apps, web apps, and node.js.
Enter RxDB — the reactive database designed specifically for JavaScript applications. With its focus on offline
capabilities and cross-platform
compatibility.
RxDB is quickly becoming a go-to solution for developers looking to streamline their workflows and deliver the best possible user experiences. So, whether you’re building a new mobile app or revamping an existing application, RxDB could be the missing piece of the puzzle you’ve been searching for.
In RxDB, you can query the current state and subscribe to all state changes, such as the result of a query or even a single field of a document if it is reactive. This works well for UI-based real-time
applications since it is simple to create and has excellent performance advantages without any backend
.
Your collections are contained in RxDatabase-Object, which also manages the synchronisation of change events. RxDB can be utilised purely on the client side.
The replication primitives plugin also allows you to create original replications that work with any protocol, including REST, Web sockets, etc.
Now, let’s see what are the salient features of RxDB?🧐
Offline-first
database that will sync with a server-side database and let your app still work when the users have no internet.- Compatible with PouchDB, CouchDB, and IBM Cloudant. There is also a plugin for
GraphQL replication
. Encryption
of single data fields to protect your user’s data.- Supports
TypeScript
for fast and secure coding. Reactive
data handling based on RxJS (allowing the handling of asynchronous events as collections, like map, filter, and reducer operations)Platform-Support
RxDB is made so that you can usethe same code
in browsers, node.js, react-native, etc…- RxDB will work as our client-side database.
- RxDB reactively handles data, so it depends on rxjs.
How can we implement RxDB in a React native application? 💻📲
Starting over with the Todo example 📝
First, create a React Native project by running this command :
npx react-native init RxDBProject
Step 1: Install Dependencies ⤵️
Then, you need to install the above packages in your React Native project.
npm install rxdb --save
# peerDependenciesnpm install rxjs --save
Step 2: Importing and Creating a Database 💻
For your database, create a file with the name InitializedDB.tsx
or another suitable name. This is how we build the database by providing a name, an adapter for storage, and a password (which must have at least 8 characters and be optional), as shown in the image below:
Step 3: Create a schema for the collection of database
To ensure that your document data always matches the JSON schema provided by your repository RxCollection
, you can use one of the several validation implementations RxDB offers.
The following TodoSchema
serves as the definition of a Todo collection
in this schema:
- The
version number
of the schema is Zero (0). - The
primary key
field contains the field name of the property that will be used as the primary key for the whole collection. - A primary key is a unique, indexed, required string that can be used to find a single document. for example, id, title, name, etc…
- The below schema has two properties of type
title
,description,
and a flagdone
for todo are completed or not. - The first property
title
is the primary key, and it represents the date the message was inserted in milliseconds. - You can also add the required property for validations to the schema.
Note 📝: A version field is represented by a number that begins with 0. When the version is greater than 0, you have to provide the migrationStrategies
to create a collection with this schema.
Step 4: Create a Collection with schema & insert a document
Get an existing collection from the database and call the collection name directly on the database, like in the below example.
// create collections
await db.addCollections({
[todoCollectionName]: {
schema: TodoSchema,
},
});// insert a document
await db[todoCollectionName].insert({
title: 'Antibiotics',
description: 'Bring Medicine from store',
done: 'true',
});
Step 5: Subscribe to query results
A query allows you to find documents in your collection. Like most other NoSQL-Databases, RxDB uses the mango-query-syntax.
It is also possible to use chained methods with the query-builder
plugin. To create a basic RxQuery
, call the .find()
method on a collection and insert selectors. The result set of normal queries is an array of documents.
In the above code, we will enter a title
and a description
with the insert()
function for a TodoList into the output, as you can see in the above image. Additionally, we can remove a document with a simple click on the delete button with the remove()
function.
findone()
will locate the data as described in the title and description, pick it up, and remove it from the database. Also added an update functionality for Todo to change the description and title with upsert()
.
You may also look into RxQuery
to learn more about it. Here, you can see the output of adding, removing, and editing Todo tasks :
The downside of offline first 👀
- It only works with
small datasets
. - Browser storage is not persistent.
Deterministic conflict
resolution is a common strategy used in offline-first databases to resolve conflicts that may arise when multiple users modify the same document while offline.- This approach involves keeping both conflicting versions of the document in storage and determining a winner by comparing their hashes. The winning document is then returned when the document is queried.
- While deterministic conflict resolution may be suitable for use cases where conflicts are rare and dropping one of the conflicting changes is not critical, it may not be the best approach for more complex or important applications.
- You have to
migrate the client database
. When developing your app, sooner or later you want to change the data layout. You want to add some new fields to documents or change their format. So you have to update the database schema and also migrate the stored documents. - Performance is not native: When you create a web-based offline first app, you cannot store data directly on the user’s filesystem. In fact, there are many layers between your JavaScript code and the filesystem of the operating system.
Yay! We used RxDB to build our first real-time database for a React Native application. 🥳
You can find the above source code on the GitHub Repository 🚀
Conclusion
The features of RxDB go well beyond what was discussed here, including encryption
, middleware hooks,
and atomic update
operations.
You can increase the functionality of this application by adding, editing, and updating features and synchronising the data with an IBM Cloudant
or CouchDB
server.
You may also check out the official RxDB GitHub repository for further information.
To learn more about engineering at Simform, check out the rest of our Engineering Blog, and visit our Simform site. To view and apply to open opportunities, visit our Careers page.