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
/ /
Sync Data

Configure a Synced Realm - React Native SDK

Puede configurar un reino para sincronizar automáticamente datos entre muchos dispositivos que tengan cada uno su propia copia local de los datos.

Para obtener más información sobre los reinos sincronizados, incluidas las instrucciones sobre cómo configurar la sincronización en una aplicación de App Services, consulte Descripción general de sincronización de dispositivos Atlas.

For more information about different realm configurations, refer to Configure a Realm.

Before you configure a realm with Flexible Sync in a React Native application:

  1. Enable Flexible Sync on the backend. You must configure Flexible Sync in the backend before you can use it with your client application.

  2. Initialize the App client.

  3. Authenticate a user in your client project.

Configurar un reino sincronizado usando los proveedores de @realm/react.

Por defecto, Realm sincroniza todos los datos del servidor antes de devolver cualquier dato. Si quieres sincronizar datos en segundo plano, lee Configure un Realm Sincronizado mientras está sin conexión.

To configure a synced realm:

  1. Import providers from @realm/react.

  2. Configurar AppProvider.

  3. Configure UserProvider and nest it within AppProvider.

  4. Configure RealmProvider for sync and nest it within UserProvider. You must set up a sync subscription. The example below uses an initial subscription, but you can also set up subscriptions in RealmProvider child components.

This is how you nest providers:

import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperSync() {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[YourObjectModel]}
sync={{
flexible: true,
initialSubscriptions: {
update(subs, realm) {
subs.add(realm.objects(YourObjectModel));
},
},
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}

Nota

Partition-Based Sync

This page covers Flexible Sync realms. Flexible Sync is the preferred mode for new apps that use Atlas Device Sync. For information about realms using the older Partition-Based Sync, refer to Partition-Based Sync.

El @realm/react AppProvider le brinda acceso a una instancia de su aplicación App Services.

Para configurar tu cliente de aplicación, pasa el string ID de la aplicación a la propiedad id de AppProvider. Encierra cualquier componente que deba acceder a la aplicación con AppProvider.

import React from 'react';
import {AppProvider} from '@realm/react';
function AppWrapper() {
return (
<View>
<AppProvider id={APP_ID}>
<MyApp />
</AppProvider>
</View>
);
}

You can find more information about AppProvider on the Connect To Atlas App Services page.

UserProvider te da acceso a un usuario de Realm.UserProvider Se requiere un para que una aplicación use los ganchos.

First, you need to configure user authentication with AppProvider and UserProvider. Then, work with authentication using the useApp() and useUser() hooks.

To set up user authentication:

  1. Envuelva todos los componentes que desea utilizar con App Services en un AppProvider.

  2. Dentro de AppProvider, envuelve todos los componentes que necesitan acceso a un usuario autenticado con un UserProvider.

  3. In UserProvider, include a fallback prop with another component that logs a user in. The app renders this component if there is no authenticated user.

  4. In the component passed to the UserProvider.fallback prop, authenticate a user with Realm.App.logIn(), which you can access with the useApp() hook.

Los componentes envueltos por UserProvider solo se renderizan si tu aplicación tiene un usuario autenticado. Estos componentes pueden acceder al usuario autenticado con el hook useUser().

import React from 'react';
import {useApp, UserProvider, AppProvider} from '@realm/react';
import {Button} from 'react-native';
function AppWrapper() {
return (
<AppProvider id={APP_ID}>
{/* If there is no authenticated user,
the app mounts the `fallback` component.
Once the user successfully authenticates,
the app unmounts the component in the
`UserProvider.fallback` prop
(the `LogIn` component in this example). */}
<UserProvider fallback={LogIn}>
{/* Components with access to the user.
These components only mount
if there's an authenticated user.*/}
<RestOfApp />
</UserProvider>
</AppProvider>
);
}
function LogIn() {
const app = useApp();
// This example uses anonymous authentication.
// However, you can use any authentication provider
// to log a user in with this pattern.
async function logInUser() {
await app.logIn(Realm.Credentials.anonymous());
}
return (
<Button
title='Log In'
onPress={logInUser}
/>
);
}

Puede encontrar más información sobre UserProvider en la página de autenticación de usuarios.

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.

To configure a synced realm:

  1. Import providers from @realm/react.

  2. Configurar AppProvider.

  3. Configure UserProvider and nest it within AppProvider.

  4. Pase sus modelos de objetos a la propiedad schema de RealmProvider.

  5. Cree un objeto FlexibleSyncConfiguration.

  6. Pasa tu objeto SyncConfiguration al prop sync o agrega el objeto en línea.

  7. Set up initial subscriptions or create a new subscription in RealmProvider child components.

  8. Add other Configuration object properties as props to RealmProvider to further configure your realm.

import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperSync() {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[YourObjectModel]}
sync={{
flexible: true,
initialSubscriptions: {
update(subs, realm) {
subs.add(realm.objects(YourObjectModel));
},
},
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}

Para obtener más información sobre cómo configurar y RealmProvider usar, consulte la página Configurar un reino.

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.

New in version realm@11.6.0.

Using AppConfiguration.baseFilePath, and Realm.BaseConfiguration.path, you can control where Realm and metadata files are stored on client devices.

To do so, set AppProvider.baseFilePath. If baseFilePath is not set, the current work directory is used. You can also set RealmProvider.sync.path for more control.

import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperSync({customBaseFilePath}) {
return (
<AppProvider id={APP_ID} baseFilePath={customBaseFilePath}>
<UserProvider fallback={LogIn}>
<RealmProvider
path={customRealmPath}
schema={[Profile]}
sync={{
flexible: true,
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}
import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
type AppWrapperSyncProps = {
customBaseFilePath: string;
};
function AppWrapperSync({customBaseFilePath}: AppWrapperSyncProps) {
return (
<AppProvider id={APP_ID} baseFilePath={customBaseFilePath}>
<UserProvider fallback={LogIn}>
<RealmProvider
path={customRealmPath}
schema={[Profile]}
sync={{
flexible: true,
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}

If baseFilePath is set, metadata is always stored in <baseFilePath>/mongodb-realm/. If baseFilePath isn't set, then metadata is stored in <Realm.defaultPath>/mongodb-realm.

El lugar exacto donde se almacena tu archivo Realm puede variar según la configuración de Realm.BaseConfiguration.path:

  • Realm.Configuration.path no está configurado y baseFilePath está configurado. Tu archivo Realm está almacenado en baseFilePath.

  • Realm.Configuation.path is set to a relative path. Your Realm file is stored relative to baseFilePath.

  • Realm.Configuration.path is an absolute path. Your Realm file is stored at Realm.Configuration.path.

Las siguientes subsecciones muestran cómo utilizar la sincronización en segundo plano para acceder a un realm sin conexión. Para hacer esto, usa un usuario en caché y un objeto OpenRealmBehaviorConfiguration.

Within RealmProvider's sync configuration, set the optional newRealmFileBehavior and existingRealmFileBehavior fields to your OpenRealmBehaviorConfiguration object to enable background synchronization.

Puedes abrir un realm inmediatamente con sincronización en segundo plano o después de un tiempo de espera.

Nota

El inicio de sesión inicial requiere una conexión de red

Cuando un usuario se registra en tu aplicación o inicia sesión por primera vez con una cuenta existente en un cliente, este debe tener conexión de red. Comprobar las credenciales de usuario en caché permite abrir un reino sin conexión, pero solo si el usuario ha iniciado sesión previamente con conexión.

Puede que desees sincronizar los cambios en segundo plano para mostrar datos parciales al usuario mientras el realm sincronizado descarga los datos del servidor, evitando así que la experiencia de usuario se bloquee. Recomendamos sincronizar los cambios en segundo plano para aplicaciones en las que el dispositivo del usuario pueda quedarse sin conexión. Para sincronizar cambios en segundo plano, abre un realm sincronizado de forma síncrona.

import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperOfflineSync() {
const realmAccessBehavior = {
type: 'openImmediately',
};
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[Profile]}
sync={{
flexible: true,
newRealmFileBehavior: realmAccessBehavior,
existingRealmFileBehavior: realmAccessBehavior,
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}
import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperOfflineSync() {
const realmAccessBehavior: Realm.OpenRealmBehaviorConfiguration = {
type: Realm.OpenRealmBehaviorType.OpenImmediately,
};
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[Profile]}
sync={{
flexible: true,
newRealmFileBehavior: realmAccessBehavior,
existingRealmFileBehavior: realmAccessBehavior,
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}

If you want to sync data but you're in an environment where it's uncertain if the user has an Internet connection, specify a timeOut. This automatically opens the realm when either:

  • transcurre el tiempo de espera.

  • the realm has completely downloaded.

If the realm doesn't finish downloading before the timeout, the initial Sync continues in the background.

import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperTimeoutSync() {
const realmAccessBehavior = {
type: 'downloadBeforeOpen',
timeOutBehavior: 'openLocalRealm',
timeOut: 1000,
};
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[Profile]}
sync={{
flexible: true,
newRealmFileBehavior: realmAccessBehavior,
existingRealmFileBehavior: realmAccessBehavior,
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}
import React from 'react';
import {AppProvider, UserProvider, RealmProvider} from '@realm/react';
function AppWrapperTimeoutSync() {
const realmAccessBehavior: Realm.OpenRealmBehaviorConfiguration = {
type: 'downloadBeforeOpen',
timeOutBehavior: 'openLocalRealm',
timeOut: 1000,
};
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[Profile]}
sync={{
flexible: true,
newRealmFileBehavior: realmAccessBehavior,
existingRealmFileBehavior: realmAccessBehavior,
}}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}

@realm/react Cuenta con proveedores de contexto y enlaces que simplifican el trabajo con el dominio sincronizado y sus datos. Consulta la página de cada proveedor para obtener más información sobre ellos y sus enlaces.

Volver

Sync Data

En esta página