safina
safina

Reputation: 212

React Native Realm Project Structure

What's the best way to implement realm in react native(project structure), when you have multiple webAPI methods and tables to store.

I'm doing the following is this a right approach or not? If not kindly suggest or provide any link.

  1. created a model folder - each js file in this folder have a model class extended with RealmObject.

  2. Created a folder for asynchronous tasks - each js file in this folder Calls web api and write data in Realm objects. Every webapi function has a sperate js file.

  3. Initially when app loads on component mount call all important async tasks and call rest of them wherever needed.

Doing this I'm unable to auto update data in realm i.e: Realm results are not dynamic we have to manually call on change to show the updated data.

Upvotes: 1

Views: 1728

Answers (1)

G Clovs
G Clovs

Reputation: 3102

There a possible structure:

I will suggest you to use the Doc of Realm -> https://realm.io/

There a possible structure: realm.js

import * as RealmDB from 'realm';

class Passenger extends RealmDB.Object {}
Passenger.schema = {
name: 'Passenger',
primaryKey: 'id',
properties: {
  'id'                : 'string',
  'firstname'         : { type: 'string', optional: true },
  'lastname'          : { type: 'string', optional: true },
  'birthdate'         : { type: 'int',    optional: true },
  'email'             : { type: 'string', optional: true },
  'phone'             : { type: 'string', optional: true },
  'child'             : { type: 'linkingObjects', objectType: 'Child', property: 'passengers' }
}
};


class Child extends RealmDB.Object {}
Child.schema = {
 name: 'Child',
 primaryKey: 'id',
  properties: {
   'id'                  : 'string',
   'name'                : 'string',
   'parents_1'           : { type: 'linkingObjects', objectType: 'Passenger', property: 'child' }
  }
 };


const realmInstance = new RealmDB({
schema: [Passenger, Child],
});
export default realmInstance;

use.js

import realm from "./realm";
export default class use {

 static writeToRealm(){
  realm.write(() => {

  let passenger = realm.create('Passenger', {
  'id'            : "..."
  'firstname'     : "...",
  'lastname'      : "...",
  "..."
  })
 }

 static readPassengers(){
  const passengers = realm.objects('Passengers');
  return passengers // Be careful Realm use List instead of Array quite the same but not! 
 }
}

Every time you want to write in your database you have to use realm.write(() => {})

Hope it's help :)

Upvotes: 1

Related Questions