Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
Sync Data

Configure a Synced Realm - React Native SDK

You can configure a realm to automatically synchronize data between many devices that each have their own local copy of the data.

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. Configure 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 gives you access to a Realm user. A UserProvider is required for an app to use the hooks.

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. Wrap all components you want to use with App Services in an 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. Configure AppProvider.

  3. Configure UserProvider and nest it within AppProvider.

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

  5. Create a FlexibleSyncConfiguration object.

  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>
);
}

For more information about configuring and using RealmProvider, check out the Configure a Realm page.

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
    Used with useRef to expose the configured realm to processes outside of RealmProvider. This can be useful for things like a client reset fallback.
  • 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

Initial login requires a network connection

When a user signs up for your app, or logs in for the first time with an existing account on a client, the client must have a network connection. Checking for cached user credentials lets you open a realm offline, but only if the user has previously logged in while online.

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:

  • the timeout period elapses.

  • 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 has Context Providers and hooks that simplify working with your synced realm and its data. Refer to each Provider's page to learn about them and their hooks.

Volver

Sync Data

En esta página