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
/ /
CRUD

CRUD - Read - React Native SDK

Read operations are queries to find your data stored in Realm. Data in Realm is live, which means that an object always reflects its most recent saved state and read operations never block. Objects automatically update in response to changes, so you can see up-to-date data in your application without running a new query.

Utilice lo siguiente @realm/react Ganchos para leer datos en un reino:

  • useObject(): Find a specific object by primary key.

  • useQuery():Obtener una colección de objetos por tipo de objeto.

These hooks return live objects, which are automatically updated when the data in the realm changes. When objects returned by these hooks are updated, the component calling the hook rerenders.

The examples on this page use the following schemas:

class Person extends Realm.Object {
static schema = {
name: 'Person',
properties: {
name: 'string',
age: 'int?',
},
};
}
class Task extends Realm.Object {
static schema = {
name: 'Task',
properties: {
_id: 'int',
name: 'string',
priority: 'int?',
progressMinutes: 'int?',
assignee: 'Person?',
},
primaryKey: '_id',
};
}
class Person extends Realm.Object<Person> {
name!: string;
age?: number;
static schema: ObjectSchema = {
name: 'Person',
properties: {
name: 'string',
age: 'int?',
},
};
}
class Task extends Realm.Object<Task> {
_id!: number;
name!: string;
priority?: number;
progressMinutes?: number;
assignee?: Person;
age?: number;
static schema: ObjectSchema = {
name: 'Task',
properties: {
_id: 'int',
name: 'string',
priority: 'int?',
progressMinutes: 'int',
assignee: 'Person?',
},
primaryKey: '_id',
};
}

If you know the primary key for a given object, you can look it up directly by passing the class type and primary key to the useObject() hook.

In the following example of a TaskItem component, we use the useObject() hook to find a task based on its primary key: _id. Then we render the task's name and priority in the UI.

const TaskItem = ({_id}) => {
const myTask = useObject(Task, _id);
return (
<View>
{myTask ? (
<Text>
{myTask.name} is a task with the priority of: {myTask.priority}
</Text>
) : null}
</View>
);
};
const TaskItem = ({_id}: {_id: number}) => {
const myTask = useObject(Task, _id);
return (
<View>
{myTask ? (
<Text>
{myTask.name} is a task with the priority of: {myTask.priority}
</Text>
) : null}
</View>
);
};

El gancho useQuery() devuelve una colección de objetos Realm que coinciden con la consulta como una Objeto Realm.Results. Una consulta básica busca todos los objetos de un tipo determinado en un reino, pero también se puede aplicar un filtro a la colección para encontrar objetos específicos.

A filter selects a subset of results based on the value(s) of one or more object properties. Realm lets you filter data using Realm Query Language, a string-based query language to constrain searches when retrieving objects from a realm.

Invoque filtered() en la colección de resultados de la consulta para filtrarla. Pase una consulta del lenguaje de consulta Realm como argumento filtered() a.

In the following example of a TaskList component, we:

  1. Obtain all Task objects by passing "Task" to the useQuery() hook.

  2. Obtain all high-priority tasks and low-progress task by passing a query to filtered().

  3. Utilice la función map para renderizar una lista de componentes Text que muestren información sobre las tareas de alta prioridad y bajo progreso.

const TaskList = () => {
const [priority, setPriority] = useState(4);
// filter for tasks with a high priority
const highPriorityTasks = useQuery(
Task,
(tasks) => {
return tasks.filtered("priority >= $0", priority);
},
[priority]
);
// filter for tasks that have just-started or short-running progress
const lowProgressTasks = useQuery(Task, tasks => {
return tasks.filtered(
'$0 <= progressMinutes && progressMinutes < $1',
1,
10,
);
});
return (
<>
<Text>Your high priority tasks:</Text>
{highPriorityTasks.map(taskItem => {
return <Text>{taskItem.name}</Text>;
})}
<Text>Your tasks without much progress:</Text>
{lowProgressTasks.map(taskItem => {
return <Text>{taskItem.name}</Text>;
})}
</>
);
};
const TaskList = () => {
const [priority, setPriority] = useState(4);
// filter for tasks with a high priority
const highPriorityTasks = useQuery(
Task,
tasks => {
return tasks.filtered('priority >= $0', priority);
},
[priority],
);
// filter for tasks that have just-started or short-running progress
const lowProgressTasks = useQuery(Task, tasks => {
return tasks.filtered(
'$0 <= progressMinutes && progressMinutes < $1',
1,
10,
);
});
return (
<>
<Text>Your high priority tasks:</Text>
{highPriorityTasks.map(taskItem => {
return <Text>{taskItem.name}</Text>;
})}
<Text>Your tasks without much progress:</Text>
{lowProgressTasks.map(taskItem => {
return <Text>{taskItem.name}</Text>;
})}
</>
);
};

Tip

Filter on Related and Embedded Object Properties

To filter a query based on a property of an embedded object or a related object, use dot-notation as if it were in a regular, nested object.

Una operación de ordenamiento permite configurar el orden en que Realm devuelve objetos consultados. Puedes ordenar en función de una o más propiedades de los objetos en la colección de resultados. Realm solo garantiza un orden coherente de los resultados si los ordenas explícitamente.

To sort a query, call the sorted() method on the query results collection.

In the following example of a TaskList component, we use the useQuery() hook to initially retrieve the set of Task objects. We then use the sorted() method to work with the data in various ways:

  1. Sort objects based on the task's name alphabetically.

  2. Ordenar objetos según el nombre de la tarea alfabéticamente en orden descendente.

  3. Ordena objetos en función de la prioridad de la tarea en orden descendente y el nombre de la tarea en orden ascendente.

  4. Ordenar objetos según el nombre del objeto asignado alfabéticamente.

Finalmente, recorremos cada lista de tareas y las renderizamos en la Interfaz de Usuario.

const TaskList = () => {
// retrieve the set of Task objects
const tasks = useQuery(Task);
// Sort tasks by name in ascending order
const tasksByName = useQuery(Task, tasks => {
return tasks.sorted('name');
});
// Sort tasks by name in descending order
const tasksByNameDescending = useQuery(Task, tasks => {
return tasks.sorted('name', true);
});
// Sort tasks by priority in descending order and then by name alphabetically
const tasksByPriorityDescendingAndName = useQuery(Task, tasks => {
return tasks.sorted([
['priority', true],
['name', false],
]);
});
// Sort Tasks by Assignee's name.
const tasksByAssigneeName = useQuery(Task, tasks => {
return tasks.sorted('assignee.name');
});
return (
<>
<Text>All tasks:</Text>
{tasks.map(task => (
<Text>{task.name}</Text>
))}
<Text>Tasks sorted by name:</Text>
{tasksByName.map(task => (
<Text>{task.name}</Text>
))}
<Text>Tasks sorted by name descending:</Text>
{tasksByNameDescending.map(task => (
<Text>{task.name}</Text>
))}
<Text>
Tasks sorted by priority descending, and name alphabetically:
</Text>
{tasksByPriorityDescendingAndName.map(task => (
<Text>
{task.name}
</Text>
))}
<Text>Tasks sorted by assignee name:</Text>
{tasksByAssigneeName.map(task => (
<Text>{task.name}</Text>
))}
</>
);
};
const TaskList = () => {
// retrieve the set of Task objects
const tasks = useQuery(Task);
// Sort tasks by name in ascending order
const tasksByName = useQuery(Task, tasks => {
return tasks.sorted('name');
});
// Sort tasks by name in descending order
const tasksByNameDescending = useQuery(Task, tasks => {
return tasks.sorted('name', true);
});
// Sort tasks by priority in descending order and then by name alphabetically
const tasksByPriorityDescendingAndName = useQuery(Task, tasks => {
return tasks.sorted([
['priority', true],
['name', false],
]);
});
// Sort Tasks by Assignee's name.
const tasksByAssigneeName = useQuery(Task, tasks => {
return tasks.sorted('assignee.name');
});
return (
<>
<Text>All tasks:</Text>
{tasks.map(task => (
<Text>{task.name}</Text>
))}
<Text>Tasks sorted by name:</Text>
{tasksByName.map(task => (
<Text>{task.name}</Text>
))}
<Text>Tasks sorted by name descending:</Text>
{tasksByNameDescending.map(task => (
<Text>{task.name}</Text>
))}
<Text>
Tasks sorted by priority descending, and name alphabetically:
</Text>
{tasksByPriorityDescendingAndName.map(task => (
<Text>
{task.name}
</Text>
))}
<Text>Tasks sorted by assignee name:</Text>
{tasksByAssigneeName.map(task => (
<Text>{task.name}</Text>
))}
</>
);
};

Tip

Sort on Related and Embedded Object Properties

Para ordenar una query basada en una propiedad de un objeto incrustado o un objeto relacionado, usa notación de puntos como si fuera un objeto anidado regular.

Volver

Crear

En esta página