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.
Requisitos previos
Antes de configurar un realm en una aplicación React Native:
Install the Realm React Native SDK
Instala el Paquete @realm/react
Configurar un reino sin sincronización
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:
Import
RealmProviderfrom@realm/react.Pase sus modelos de objetos a la propiedad
schema.Agregue otras propiedades de objeto de configuración como accesorios a
RealmProviderpara 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.
Opciones de configuración
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
useRefpara exponer el dominio configurado a procesos externos aRealmProvider. 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
fallbackprop isn't needed.
Configura un Realm en Memoria
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.
Encrypt a Realm
To encrypt a realm file on disk, refer to Encrypt a Realm.
Configurar un Realm sincronizado
To open a realm that synchronizes data with Atlas using Device Sync, refer to Open a Synced Realm.
Expose More Than One 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
RealmProviderdirectly from@realm/react, it is a separate Context object. That object's providers and hooks can't be unsynced with Context objects created usingcreateRealmContext.
Create Separate Context Objects
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], });
Extract Providers and Hooks
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;
Utilice proveedores y ganchos con espacios de nombres
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... }
Acceso a un Realm sin proporcionar un esquema
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 Providers and Hooks
@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. | | ||
Devuelve un objeto ( | | ||
Devuelve una colección de objetos ( | |