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

Quick Start - React Native SDK

Esta p谩gina demuestra c贸mo utilizar Realm utilizando el SDK de React Native.

Antes de comenzar, instala el SDK Realm React Native.

@realm/reaccionar Es un paquete utilizado en el SDK de React Native. Proporciona ganchos de React con reconocimiento de estado para datos de Realm. Estos ganchos supervisan los datos de Realm y rerenderizan los componentes seg煤n sea necesario.

La documentaci贸n del SDK de React Native utiliza el @realm/react Paquete npm para ejemplos y descripci贸n de conceptos.

Refer to these pages for more details:

After installing the realm and @realm/react packages, there are a few more things to set up before you can access your realm and work with local data:

  • Define tus modelos de objetos

  • Configure a realm by creating a realm context object, extracting hooks, and setting up providers

Your application's object models define the data types that you can store within a realm. Each object model becomes a Realm object type.

To define a Realm object model:

  1. Crea una clase que extienda Realm.Object.

  2. Agregar un campo schema.

  3. For the schema value, create an object that contains properties and name properties. The name value must be unique among object types in your realm.

// Define your object model
export class Profile extends Realm.Object<Profile> {
_id!: BSON.ObjectId;
name!: string;
static schema: ObjectSchema = {
name: 'Profile',
properties: {
_id: 'objectId',
name: {type: 'string', indexed: 'full-text'},
},
primaryKey: '_id',
};
}

To learn more, refer to Define a Realm Object Model.

Before you can work with data, you need to configure a realm. This means you need to set up context and providers from @realm/react. To learn more, refer to Configure a Realm.

To configure and access a local realm:

  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 props a RealmProvider.

import React from 'react';
import {RealmProvider} from '@realm/react';
// Import your models
import {Profile} from '../../../models';
export const AppWrapper = () => {
return (
<RealmProvider schema={[Profile]}>
<RestOfApp />
</RealmProvider>
);
};

After you have a data model and a configured realm, you can create, read, update, or delete Realm objects.

You must nest components that perform these operations inside of RealmProvider. The useRealm(), useQuery(), and useObject() hooks enable you to perform read and write operations in your realm.

For detailed descriptions of RealmProvider and its hooks, refer to RealmProvider (@realm/react)

@realm/react provides hooks to help you find a collection of Realm objects or a single Realm object.

As part of useQuery(), you can filter or sort the results using Realm Query Language (RQL).

import React from 'react';
import {useQuery} from '@realm/react';
import {Profile} from '../../models';
export const Read = () => {
// Find
const profiles = useQuery(Profile);
// Sort
const sortedProfiles = useQuery(Profile, profiles => {
return profiles.sorted('name', false);
});
// Filter
const filteredProfiles = useQuery(Profile, profiles => {
return profiles.filtered('name == "testProfile"');
});
// ... rest of component
};

To learn more, refer to CRUD - Read and Query Data.

Sometimes, you may need to use Realm read operations, but not at the top level of your React Native component. Because hooks only work at the top level of components, you can't use the @realm/react hooks in these situations.

En su lugar, puedes utilizar Realm.objects para colecciones o Realm.objectForPrimaryKey para un objeto individual.

After accessing the realm with useRealm(), you can create, update, and delete objects inside of the realm. All operations must be in a Realm.write() transaction block.

To learn more, refer to Write Transactions.

To create a new Realm object, specify the object type, pass in the object's initial values, and add it to the realm in a write transaction block.

import React, {useState} from 'react';
import {Text, TextInput, View} from 'react-native';
import {BSON} from 'realm';
import {useRealm} from '@realm/react';
import {Profile} from '../../models';
export const Create = () => {
const realm = useRealm();
const [profileName, setProfileName] = useState('');
const addProfile = () => {
realm.write(() => {
realm.create(Profile, {
_id: new BSON.ObjectId(),
name: profileName,
});
});
};
return (
<View>
<Text>Create</Text>
<TextInput
onChangeText={setProfileName}
value={profileName}
placeholder="Profile name..."
/>
<Button
title="Add Profile"
onPress={addProfile}
/>
</View>
);
};

To learn more, refer to CRUD - Create.

To update a Realm object, update its properties in a write transaction block.

import React, {useState} from 'react';
import {Text, FlatList, View, Pressable, TextInput} from 'react-native';
import {useRealm, useQuery} from '@realm/react';
import {Profile} from '../../models';
export const Update = () => {
const realm = useRealm();
const profiles = useQuery(Profile);
const [profileToUpdate, setProfileToUpdate] = useState('');
const [newProfileName, setNewProfileName] = useState('');
const updateProfile = () => {
const toUpdate = realm
.objects(Profile)
.filtered('name == $0', profileToUpdate);
realm.write(() => {
toUpdate[0].name = newProfileName;
});
};
return (
<View>
<Text>Update</Text>
{profiles.length ? (
<View>
<Text>Profiles: </Text>
<FlatList
scrollEnabled={false}
data={profiles}
horizontal={true}
renderItem={({item}) => (
<Pressable
onPress={() => {
setProfileToUpdate(item.name);
}}>
<Text
>
{item.name}
</Text>
</Pressable>
)}
keyExtractor={item => item.name}
/>
</View>
) : (
<Text>馃洃 No profiles found</Text>
)}
{profileToUpdate && (
<TextInput
style={styles.textInput}
onChangeText={setNewProfileName}
value={newProfileName}
placeholder="New profile name..."
/>
)}
<Button
title="Update profile"
onPress={updateProfile}
/>
</View>
);
};

To learn more, refer to CRUD - Update.

To delete a Realm object, pass the object to Realm.delete() within a write transaction block.

import React, {useState} from 'react';
import {Text, FlatList, View, Pressable} from 'react-native';
import {useRealm, useQuery} from '@realm/react';
import {Profile} from '../../models';
export const Delete = () => {
const realm = useRealm();
const profiles = useQuery(Profile);
const [profileToDelete, setProfileToDelete] = useState('');
const deleteProfile = () => {
const toDelete = realm
.objects(Profile)
.filtered('name == $0', profileToDelete);
realm.write(() => {
realm.delete(toDelete);
});
};
return (
<View>
<Text>Delete</Text>
{profiles.length ? (
<View>
<Text>Profiles: </Text>
<FlatList
scrollEnabled={false}
data={profiles}
horizontal={true}
renderItem={({item}) => (
<Pressable
onPress={() => {
setProfileToDelete(item.name);
}}>
<Text
>
{item.name}
</Text>
</Pressable>
)}
keyExtractor={item => item.name}
/>
</View>
) : (
<Text>馃洃 No profiles found</Text>
)}
<Button
title="Delete profile"
onPress={deleteProfile}
/>
</View>
);
};

To learn more, refer to CRUD - Delete.

After getting your non-sync realm running, you can add Atlas Device Sync. This enables your realm data to sync with a MongoDB Atlas cluster and other client devices.

Para usar Device Sync, necesitas configurar un par de cosas m谩s:

  • Create a backend in Atlas App Services (see the prerequisites below)

  • Configura un realm Flexible Sync en lugar de uno que no sea de sincronizaci贸n.

To use a Device Sync, you need to configure three @realm/react providers:

After you initialize your App, authenticate a user, and define your object model, you can configure a synced realm. This is similar to configuring a local realm. However, you need to add some additional props to the RealmProvider.

Add the sync prop to RealmProvider and pass it a FlexibleSyncConfiguration object. This sync object must contain flexible: true You should also add initial subscriptions. You must have at least one sync subscription before you can read or write synced data.

Para configurar y acceder a un realm sincronizado:

  1. Initialize the App using AppProvider. You can find your App ID in the App Services UI.

  2. Authenticate a User with UserProvider

  3. Configure a synced realm with RealmProvider

import React from 'react';
import {Credentials} from 'realm';
import {RealmProvider, AppProvider, UserProvider, useApp} from '@realm/react';
// Import your models
import {Profile} from '../../../models';
// Expose a sync realm
export function AppWrapperSync() {
return (
<AppProvider id={APP_ID}>
<UserProvider fallback={LogIn}>
<RealmProvider
schema={[Profile]}
sync={{
flexible: true,
onError: (_session, error) => {
console.log(error);
},
initialSubscriptions: {
update(subs, realm) {
subs.add(realm.objects('Profile'));
},
rerunOnOpen: true,
},
}}
fallback={fallback}>
<RestOfApp />
</RealmProvider>
</UserProvider>
</AppProvider>
);
}

The syntax to create, read, update, and delete objects in a synced realm is identical to the syntax for non-synced realms. While you work with local data, a background thread efficiently integrates, uploads, and downloads changesets.

Para obtener m谩s informaci贸n, consulta Configurar una Synced Realm.

Si te interesa una experiencia guiada, puedes leer nuestro tutorial del SDK de Realm para React Native. Este tutorial implementa y ampl铆a una aplicaci贸n base de React Native creada con Realm y Device Sync.

You could also use the template app to experiment with the React Native SDK on your own. To set up the template app, refer to Template Apps in the Atlas App Services documentation.

Next

Bienvenido a la Docs de Atlas Device SDK

En esta p谩gina