Realm database helps your app save and read data quickly and easily on the device. It works offline and keeps your data safe.
Realm database in React Native
Introduction
Syntax
React Native
import Realm from 'realm'; const CarSchema = { name: 'Car', properties: { make: 'string', model: 'string', miles: 'int', }, }; const realm = new Realm({schema: [CarSchema]});
Define your data structure using a schema object.
Create a Realm instance with your schema to start using the database.
Examples
React Native
const DogSchema = {
name: 'Dog',
properties: {
name: 'string',
age: 'int',
},
};React Native
realm.write(() => {
realm.create('Car', {make: 'Toyota', model: 'Corolla', miles: 10000});
});React Native
const cars = realm.objects('Car');Sample App
This React Native app uses Realm to store and show a list of cars. It adds a car if none exists and displays all cars stored.
React Native
import React, {useEffect, useState} from 'react'; import {View, Text} from 'react-native'; import Realm from 'realm'; const CarSchema = { name: 'Car', properties: { make: 'string', model: 'string', miles: 'int', }, }; export default function App() { const [cars, setCars] = useState([]); useEffect(() => { const realm = new Realm({schema: [CarSchema]}); // Add a car if none exists realm.write(() => { if (realm.objects('Car').length === 0) { realm.create('Car', {make: 'Honda', model: 'Civic', miles: 5000}); } }); // Get all cars const allCars = realm.objects('Car'); setCars(allCars.map(car => `${car.make} ${car.model} - ${car.miles} miles`)); // Cleanup return () => { realm.close(); }; }, []); return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <Text style={{fontSize: 20, marginBottom: 10}}>Cars in Realm DB:</Text> {cars.map((car, index) => ( <Text key={index}>{car}</Text> ))} </View> ); }
Important Notes
Always open Realm inside useEffect or lifecycle methods to avoid multiple instances.
Use realm.write() to add or change data safely.
Remember to close Realm when the component unmounts to free resources.
Summary
Realm stores data locally on the device for fast access.
Define schemas to tell Realm what data looks like.
Use write transactions to add or update data.
Practice
1. What is the primary purpose of using Realm database in a React Native app?
easy
Solution
Step 1: Understand Realm's role
Realm is a local database designed to store data on the device itself.Step 2: Compare options
Options A, B, and C describe unrelated functions like navigation, remote servers, and UI styling, which Realm does not handle.Final Answer:
To store data locally on the device for fast access -> Option BQuick Check:
Realm = local data storage [OK]
Hint: Realm is for local data, not UI or navigation [OK]
Common Mistakes:
- Confusing Realm with remote databases
- Thinking Realm manages UI or navigation
- Assuming Realm is a cloud service
2. Which of the following is the correct way to define a Realm schema for a
Task object with a string name and a boolean completed property?easy
Solution
Step 1: Check Realm property types
Realm expects property types as lowercase strings like 'string' and 'bool'.Step 2: Compare options
const TaskSchema = {name: 'Task', properties: {name: 'string', completed: 'bool'}}; uses correct lowercase strings. Options A, C, and D use incorrect types or JavaScript types instead of strings.Final Answer:
const TaskSchema = {name: 'Task', properties: {name: 'string', completed: 'bool'}}; -> Option AQuick Check:
Property types are lowercase strings [OK]
Hint: Use lowercase strings for property types in schema [OK]
Common Mistakes:
- Using JavaScript types instead of strings
- Capitalizing type names incorrectly
- Omitting the 'properties' key
3. Given the following code snippet, what will be the output of
console.log(tasks.length);?
const realm = await Realm.open({schema: [TaskSchema]});
realm.write(() => {
realm.create('Task', {name: 'Buy milk', completed: false});
realm.create('Task', {name: 'Walk dog', completed: true});
});
const tasks = realm.objects('Task');
console.log(tasks.length);medium
Solution
Step 1: Analyze write transaction
Two Task objects are created inside the write block, so two entries are added.Step 2: Check objects query
realm.objects('Task') returns all Task objects, so length should be 2.Final Answer:
2 -> Option CQuick Check:
Created 2 tasks, length = 2 [OK]
Hint: Count created objects inside write block [OK]
Common Mistakes:
- Forgetting to use write block for create
- Assuming objects() returns empty before commit
- Confusing length with undefined
4. What is wrong with this Realm write transaction code? (Assume the
TaskSchema defines name as the primary key)
realm.write(() => {
realm.create('Task', {name: 'Read book', completed: false});
});
realm.write(() => {
realm.create('Task', {name: 'Read book', completed: true});
});medium
Solution
Step 1: Check schema requirements
Withnameas primary key, creating an object with the same primary key without update flag causes error.Step 2: Analyze code behavior
The first create succeeds. The second create uses the samename(primary key) without update flag, so it throws an error.Final Answer:
The second create will throw an error because a Task with the same primary key already exists -> Option AQuick Check:
Duplicate primary key without update flag causes error [OK]
Hint: Use primary key and update flag to avoid create errors [OK]
Common Mistakes:
- Assuming multiple writes are forbidden
- Thinking create auto-updates without flags
- Ignoring primary key requirements
5. You want to update the
completed status of a Task object named 'Laundry' to true. (Assume the Task schema defines name as the primary key) Which code snippet correctly performs this update in Realm?hard
Solution
Step 1: Understand update with create
Realm updates existing objects if you passtrueas the third argument to create.Step 2: Check each option
realm.write(() => { realm.create('Task', {name: 'Laundry', completed: true}, true); }); uses true flag correctly. realm.write(() => { realm.create('Task', {name: 'Laundry', completed: true}); }); tries to create without update flag, causing error. realm.write(() => { realm.objects('Task').filtered('name == "Laundry"').completed = true; }); tries to assign directly to filtered results, which is invalid. realm.write(() => { realm.update('Task', {name: 'Laundry', completed: true}); }); uses a non-existent update method.Final Answer:
realm.write(() => { realm.create('Task', {name: 'Laundry', completed: true}, true); }); -> Option DQuick Check:
Use create with true flag to update [OK]
Hint: Use true flag in create to update existing objects [OK]
Common Mistakes:
- Forgetting the update flag for updates
- Trying to assign directly to query results
- Using non-existent Realm methods
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
