The examples on this page use the following schema:
class Task extends Realm.Object { static schema = { name: 'Task', properties: { _id: 'int', name: 'string', priority: 'int?', progressMinutes: 'int?', assignee: 'Person?', }, primaryKey: '_id', }; }
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', }; }
Actualizar un objeto
Puede agregar, modificar o eliminar propiedades de un objeto Realm de la misma manera que actualizaría cualquier otro objeto JavaScript. Pero debes hacerlo dentro de una transacción de escritura.
En el siguiente ejemplo de un TaskItem componente, nosotros:
Get access to the opened realm instance by calling the
useRealm()hook within the component.Retrieve a task by calling
useObject()with "Task" and the_idparameter of the component.Create a component method
incrementTaskProgress()that performs a write transaction and increments the task'sprogressMinutes.Renderizar el
namey elprogressMinutesde la tarea en la Interfaz de Usuario.Añadir un onPressevento en el botón "incrementar" que llama
incrementTaskProgress()a.
const TaskItem = ({_id}) => { const realm = useRealm(); const myTask = useObject(Task, _id); const incrementTaskProgress = () => { if (myTask) { realm.write(() => { myTask.progressMinutes += 1; }); } }; if (myTask) { return ( <> <Text>Task: {myTask.name}</Text> <Text>Progress made (in minutes):</Text> <Text>{myTask.progressMinutes}</Text> <Button onPress={() => incrementTaskProgress()} title='Increment Task Progress' /> </> ); } else { return <></>; } };
const TaskItem = ({_id}: {_id: number}) => { const realm = useRealm(); const myTask = useObject(Task, _id); const incrementTaskProgress = () => { if (myTask) { realm.write(() => { myTask.progressMinutes! += 1; }); } }; if (myTask) { return ( <> <Text>Task: {myTask.name}</Text> <Text>Progress made (in minutes):</Text> <Text>{myTask.progressMinutes}</Text> <Button onPress={() => incrementTaskProgress()} title='Increment Task Progress' /> </> ); } else { return <></>; } };
Tip
Actualizar objetos relacionados y incrustados
To update a property of an embedded object or a related object, modify the property with dot-notation or bracket-notation as if it were in a regular, nested object.
Upsert an Object
Para la inserción de un objeto dentro de una transacción de escritura, llama a Realm.create() con el modo de actualización establecido en modified. La operación inserta un nuevo objeto con la llave primaria proporcionada o actualiza un objeto existente que ya tiene esa llave primaria.
Nota
Upserting Requires Realm.create()
You must call Realm.create() within a write transaction to upsert an object. This is different than creating a new Realm Objects by calling the new operator.
En el siguiente ejemplo de un componente de CreateTaskItem:
Get access to the opened realm instance by calling the
useRealm()hook within the component.Perform a write transaction, and create a
Taskobject with an_idvalue of1234.Call
Realm.create()inside the write transaction to upsert aTaskobject by specifying the same_idand a different``progressMinutes`` and the update mode set to "modified".Render the task's
nameandprogressMinutesin the UI, showing the modified progress.
const CreateTaskItem = () => { const realm = useRealm(); let myTask; realm.write(() => { // Add a new Task to the realm. Since no task with ID 1234 // has been added yet, this adds the instance to the realm. myTask = realm.create( 'Task', {_id: 1234, name: 'Wash the car', progressMinutes: 0}, 'modified', ); // If an object exists, setting the third parameter (`updateMode`) to // "modified" only updates properties that have changed, resulting in // faster operations. myTask = realm.create( 'Task', {_id: 1234, name: 'Wash the car', progressMinutes: 5}, 'modified', ); }); return ( <> <Text>{myTask.name}</Text> <Text>Progress made (in minutes):</Text> <Text>{myTask.progressMinutes}</Text> </> ); };
const CreateTaskItem = () => { const realm = useRealm(); const myTask: Realm.Object = realm.write(() => { // Add a new Task to the realm. Since no Task with ID 1234 // has been added yet, this adds the instance to the realm. realm.create( 'Task', {_id: 1234, name: 'Wash the car', progressMinutes: 0}, 'modified', ); // If an object exists, setting the third parameter (`updateMode`) to // "modified" only updates properties that have changed, resulting in // faster operations. return realm.create( 'Task', {_id: 1234, name: 'Wash the car', progressMinutes: 5}, 'modified', ); }); return ( <> <Text>{myTask.name}</Text> <Text>Progress made (in minutes):</Text> <Text>{myTask.progressMinutes}</Text> </> ); };
Actualizar colección por lotes
To apply an update to a collection of objects, iterate through the collection (e.g. with for...of). In the loop, update each object individually.
In the following example of a TaskDashboard component, we:
Get access to the opened realm instance by calling the
useRealm()hook within the component.Recupera todas las tareas en la instancia Realm pasando
Taskal ganchouseQuery().Create a component method
resetProgressOnAllTasks()that performs a write transaction. Within that write transaction, we bulk update all tasks by looping through them usingfor...ofand set theirprogressMinutesto 0.Map through the tasks to render a list of
Textcomponents displaying each task'snameandprogressMinutes.
const TaskDashboard = () => { const realm = useRealm(); const tasks = useQuery(Task); const resetProgressOnAllTasks = () => { realm.write(() => { for (const task of tasks) { task.progressMinutes = 0; } }); }; return ( <> {tasks.map(task => { <Text> {task.name} has {task.progressMinutes} minutes progressed </Text>; })} <Button onPress={resetProgressOnAllTasks} title='Reset Progress' /> </> ); };