0
0
React Nativemobile~5 mins

Realm database in React Native

Choose your learning style9 modes available
Introduction

Realm database helps your app save and read data quickly and easily on the device. It works offline and keeps your data safe.

You want to save user notes or settings locally on the phone.
Your app needs to work without internet and sync later.
You want to store lists of items like tasks or contacts.
You want a simple way to manage data without complex setup.
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
This schema defines a Dog with a name and age.
React Native
const DogSchema = {
  name: 'Dog',
  properties: {
    name: 'string',
    age: 'int',
  },
};
Add a new Car object inside a write transaction.
React Native
realm.write(() => {
  realm.create('Car', {make: 'Toyota', model: 'Corolla', miles: 10000});
});
Get all Car objects stored in the database.
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>
  );
}
OutputSuccess
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.