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.
Requisitos previos
Before you configure a realm with Flexible Sync in a React Native application:
Enable Flexible Sync on the backend. You must configure Flexible Sync in the backend before you can use it with your client application.
Authenticate a user in your client project.
Configurar un Realm sincronizado
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:
Import providers from
@realm/react.Configurar
AppProvider.Configure
UserProviderand nest it withinAppProvider.Configure
RealmProviderfor sync and nest it withinUserProvider. You must set up a sync subscription. The example below uses an initial subscription, but you can also set up subscriptions inRealmProviderchild 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.
AppProvider
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
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:
Envuelva todos los componentes que desea utilizar con App Services en un
AppProvider.Dentro de
AppProvider, envuelve todos los componentes que necesitan acceso a un usuario autenticado con unUserProvider.In
UserProvider, include afallbackprop with another component that logs a user in. The app renders this component if there is no authenticated user.In the component passed to the
UserProvider.fallbackprop, authenticate a user withRealm.App.logIn(), which you can access with theuseApp()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
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:
Import providers from
@realm/react.Configurar
AppProvider.Configure
UserProviderand nest it withinAppProvider.Pase sus modelos de objetos a la propiedad
schemadeRealmProvider.Cree un objeto FlexibleSyncConfiguration.
Pasa tu objeto
SyncConfigurational propsynco agrega el objeto en línea.Set up initial subscriptions or create a new subscription in
RealmProviderchild components.Add other Configuration object properties as props to
RealmProviderto 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.
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.
Open Synced Realm at Specific Path
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.pathno está configurado ybaseFilePathestá configurado. Tu archivo Realm está almacenado enbaseFilePath.Realm.Configuation.pathis set to a relative path. Your Realm file is stored relative tobaseFilePath.Realm.Configuration.pathis an absolute path. Your Realm file is stored atRealm.Configuration.path.
Access a Synced Realm While Offline
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.
Acceso inmediato con sincronización en segundo plano
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> ); }
Acceso después del tiempo de espera con sincronización en segundo plano
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 Providers and Hooks
@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.