Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Realm Files

Configurar un Realm - React Native SDK

El SDK de React Native de Realm y @realm/react El paquete proporciona muchas opciones de configuración para su reino.

How you configure your realm determines the capabilities of your realm and how you work with your data. This page contains information about how to configure your realm in various ways.

Antes de configurar un realm en una aplicación React Native:

  1. Install the Realm React Native SDK

  2. Instala el Paquete @realm/react

RealmProvider es un contenedor que expone un realm a sus componentes secundarios. Se configura el realm pasando props a RealmProvider.

Cuando RealmProvider se renderiza, se abre el realm. Esto significa que los componentes secundarios no pueden acceder al realm si el renderizado falla.

Para configurar un reino no sincronizado:

  1. Import RealmProvider from @realm/react.

  2. Pase sus modelos de objetos a la propiedad schema.

  3. Agregue otras propiedades de objeto de configuración como accesorios a RealmProvider para configurar su reino.

import React from 'react';
import {RealmProvider} from '@realm/react';
function AppWrapperLocal() {
return (
<RealmProvider schema={[YourObjectModel]}>
<RestOfApp />
</RealmProvider>
);
}

Para obtener una lista de proveedores y ganchos utilizados en un reino no sincronizado, consulte Proveedores y ganchos de @realm/react.

Puedes configurar RealmProvider estableciendo props que coincidan con las propiedades de un objeto de configuración. También puedes establecer los props fallback y realmRef.

  • realmRef
    Se usa con useRef para exponer el dominio configurado a procesos externos a RealmProvider. Esto puede ser útil para, por ejemplo, un respaldo tras el restablecimiento de un cliente.
  • fallback
    Rendered while waiting for the realm to open. Local realms usually open fast enough that the fallback prop isn't needed.

Para crear un reino que se ejecute completamente en la memoria sin escribirse en un archivo, pase true a la propiedad inMemory en su RealmProvider:

import React from 'react';
import {Realm, RealmProvider} from '@realm/react';
function AppWrapperLocal() {
return (
<RealmProvider inMemory={true}>
<RestOfApp />
</RealmProvider>
);
}

In-memory realms may use disk space if memory is running low, but files created by an in-memory realm are deleted when you close the realm.

To encrypt a realm file on disk, refer to Encrypt a Realm.

To open a realm that synchronizes data with Atlas using Device Sync, refer to Open a Synced Realm.

The @realm/react package exposes realms in your application using React Context objects and Provider components. You can access realms with React hooks.

To expose more than one realm, consider the following:

  • Each realm needs its own Context object, created with createRealmContext().

  • The providers and hooks within each context should be namespaced so that it's easy to reason about the realm you're working with.

  • If you import RealmProvider directly from @realm/react, it is a separate Context object. That object's providers and hooks can't be unsynced with Context objects created using createRealmContext.

You can open more than one realm at a time by creating additional Context objects using createRealmContext().

import React from 'react';
import {
Realm,
AppProvider,
UserProvider,
createRealmContext,
} from '@realm/react';
class SharedDocument extends Realm.Object {
static schema = {
name: 'SharedDocument',
properties: {
_id: 'objectId',
owner_id: 'objectId',
title: 'string',
createdDate: 'date',
},
primaryKey: '_id',
};
}
class LocalDocument extends Realm.Object {
static schema = {
name: 'LocalDocument',
properties: {
_id: 'objectId',
name: 'string',
createdDate: 'date',
},
};
}
// Create Shared Document context object.
const SharedRealmContext = createRealmContext({
schema: [SharedDocument],
});
// Create Local Document context object.
const LocalRealmContext = createRealmContext({
schema: [LocalDocument],
});
import React from 'react';
import {
Realm,
AppProvider,
UserProvider,
createRealmContext,
} from '@realm/react';
class SharedDocument extends Realm.Object<SharedDocument> {
_id!: Realm.BSON.ObjectId;
owner_id!: Realm.BSON.ObjectId;
title!: string;
createdDate?: Date;
static schema: ObjectSchema = {
name: 'SharedDocument',
properties: {
_id: 'objectId',
owner_id: 'objectId',
title: 'string',
createdDate: 'date',
},
primaryKey: '_id',
};
}
class LocalDocument extends Realm.Object<LocalDocument> {
_id!: Realm.BSON.ObjectId;
name!: string;
createdDate?: Date;
static schema: ObjectSchema = {
name: 'LocalDocument',
properties: {
_id: 'objectId',
name: 'string',
createdDate: 'date',
},
};
}
// Create Shared Document context object.
const SharedRealmContext = createRealmContext({
schema: [SharedDocument],
});
// Create Local Document context object.
const LocalRealmContext = createRealmContext({
schema: [LocalDocument],
});

You need to extract providers and hooks from each Context object. You should namespace the providers and hooks using destructuring. This makes it easier to reason about the realm you're working with.

Refer to Non-Synced RealmProvider Hooks to see which hooks are available for a RealmProvider that isn't using Device Sync.

// Namespace the Shared Document context's providers and hooks.
const {
RealmProvider: SharedDocumentRealmProvider,
useRealm: useSharedDocumentRealm,
} = SharedRealmContext;
// Namespace the Local Document context's providers and hooks.
const {
RealmProvider: LocalDocumentRealmProvider,
useRealm: useLocalDocumentRealm,
} = LocalRealmContext;

After extracting a Context object's providers and hooks, you can use them in your app's components. Child components inside of extracted providers have access to extracted hooks.

function TwoRealmsWrapper() {
return (
<View>
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
{/* This is a Flexible Sync realm. */}
<SharedDocumentRealmProvider sync={{flexible: true}}>
<AppSectionOne />
</SharedDocumentRealmProvider>
</UserProvider>
</AppProvider>
{/* This is a separate local-only realm. */}
<LocalDocumentRealmProvider>
<AppSectionTwo />
</LocalDocumentRealmProvider>
</View>
);
}
function AppSectionOne() {
const realm = useSharedDocumentRealm();
// Work with shared documents...
}
function AppSectionTwo() {
const realm = useLocalDocumentRealm();
// Work with local documents...
}

After a realm has been created on a device, you don't need to always pass in a schema to access the realm. Instead, you can use RealmProvider without passing any object models to its schema property. The realm's schema is derived from the existing realm file at Realm.defaultPath.

Accessing a realm without providing a schema only works for local realms. You must always pass a schema when using a Synced realm.

import React from 'react';
import {RealmProvider} from '@realm/react';
function AppWrapper() {
return (
// To access a realm at the default path, do not pass any configuration.
// Requires a realm that has already been created.
<RealmProvider>
<RestOfApp />
</RealmProvider>
);
}

@realm/react has providers and hooks that simplify working with your non-sync realm and its data.

Provider/Hook
Descripción
Ejemplo

A wrapper that exposes a realm to its child components, which have access to hooks that let you read, write, and update data.

Devuelve la instancia de Realm abierta por RealmProvider.

const realm = useRealm();

Devuelve un objeto (Realm.Object<T>) de un tipo y valor de clave principal dados. Se actualiza al recibir cualquier cambio en el objeto devuelto. Devuelve null si el objeto no existe o se ha eliminado.

const myTask = useObject(Task, _id);

Devuelve una colección de objetos (Realm.Results<T & Realm.Object T>) de un tipo determinado. Actualizaciones sobre cualquier cambio en cualquier objeto de la colección. Retorna un arreglo vacío si la colección está vacía.

const tasks = useQuery(Task);

Volver

Realm Files

En esta página