RxDB Quickstart
Welcome to the RxDB Quickstart. Here we'll learn how to create a simple real-time app with the RxDB database that is able to store and query data persistently in a browser and does realtime updates to the UI on changes.
Pick a Storageβ
RxDB is able to run in a wide range of JavaScript runtimes like browsers, mobile apps, desktop and servers. Therefore different storage engines exist that ensure the best performance depending on where RxDB is used.
Use this for the simplest browser setup and very small datasets. It has a tiny bundle size and works anywhere localStorage is available, but is not optimized for large data or heavy writes.
import { getRxStorageLocalstorage } from 'rxdb/plugins/storage-localstorage';
let storage = getRxStorageLocalstorage();
Which storage should I use?
RxDB provides a wide range of storages depending on your JavaScript runtime and performance needs.
- In the Browser: Use the LocalStorage storage for simple setup and small build size. For bigger datasets, use either the dexie.js storage (free) or the IndexedDB RxStorage if you have π premium access which is a bit faster and has a smaller build size.
- In Electron and ReactNative: Use the SQLite RxStorage if you have π premium access or the trial-SQLite RxStorage for tryouts.
- In Capacitor: Use the SQLite RxStorage if you have π premium access, otherwise use the localStorage storage.
Dev-Modeβ
When you use RxDB in development, you should always enable the dev-mode plugin, which adds helpful checks and validations, and tells you if you do something wrong.
import { addRxPlugin } from 'rxdb/plugins/core';
import { RxDBDevModePlugin } from 'rxdb/plugins/dev-mode';
addRxPlugin(RxDBDevModePlugin);
Schema Validationβ
Schema validation is required when using dev-mode and recommended (but optional) in production. Wrap your storage with the AJV schema validator to ensure all documents match your schema before being saved.
import { wrappedValidateAjvStorage } from 'rxdb/plugins/validate-ajv';
storage = wrappedValidateAjvStorage({ storage });
Create a Databaseβ
A database is the topβlevel container in RxDB, responsible for managing collections, coordinating persistence, and providing reactive change streams.
import { createRxDatabase } from 'rxdb/plugins/core';
const myDatabase = await createRxDatabase({
name: 'mydatabase',
storage: storage
});
Add a Collectionβ
An RxDatabase contains RxCollections for storing and querying data. A collection is similar to an SQL table, and individual records are stored in the collection as JSON documents. An RxDatabase can have as many collections as you need. Add a collection with a schema to the database:
await myDatabase.addCollections({
// name of the collection
todos: {
// we use the JSON-schema standard
schema: {
version: 0,
primaryKey: 'id',
type: 'object',
properties: {
id: {
type: 'string',
maxLength: 100 // <- the primary key must have maxLength
},
name: {
type: 'string'
},
done: {
type: 'boolean'
},
timestamp: {
type: 'string',
format: 'date-time'
}
},
required: ['id', 'name', 'done', 'timestamp']
}
}
});
Update a Documentβ
In the first found document, set done to true:
const firstDocument = foundDocuments[0];
await firstDocument.patch({
done: true
});
Delete a documentβ
Delete the document so that it can no longer be found in queries:
await firstDocument.remove();
Observe a Queryβ
Subscribe to data changes so that your UI is always up-to-date with the data stored on disk. RxDB allows you to subscribe to data changes even when the change happens in another part of your application, another browser tab, or during database replication/synchronization:
const observable = myDatabase.todos.find({
selector: {
done: {
$eq: false
}
}
}).$ // get the observable via RxQuery.$;
observable.subscribe(notDoneDocs => {
console.log('Currently have ' + notDoneDocs.length + ' things to do');
// -> here you would re-render your app to show the updated document list
});
Observe a Document valueβ
You can also subscribe to the fields of a single RxDocument. Add the $ sign to the desired field and then subscribe to the returned observable.
myDocument.done$.subscribe(isDone => {
console.log('done: ' + isDone);
});
Sync the Clientβ
RxDB has multiple replication plugins to replicate database state with a server.
The easiest way to replicate data between your clients' devices is the WebRTC replication plugin that replicates data between devices without a centralized server. This makes it easy to try out replication without having to host anything:
import {
replicateWebRTC,
getConnectionHandlerSimplePeer
} from 'rxdb/plugins/replication-webrtc';
replicateWebRTC({
collection: myDatabase.todos,
connectionHandlerCreator: getConnectionHandlerSimplePeer({}),
topic: '', // <- set any app-specific room id here.
secret: 'mysecret',
pull: {},
push: {}
})
Next stepsβ
You are now ready to dive deeper into RxDB.
- Start reading the full documentation here.
- There is a full implementation of the quickstart guide so you can clone that repository and play with the code.
- For frameworks and runtimes like Angular, React Native and others, check out the list of example implementations.
- Also please continue reading the documentation, join the community on our Discord chat, and star the GitHub repo.
- If you are using RxDB in a production environment and are able to support its continued development, please take a look at the π Premium package which includes additional plugins and utilities.