I am trying to update multiple object in realm react native using for loop like this:
let pendingReadings = database.objects('Readings').filtered('synced = false');
database.write(() => {
for (var k=0;k<pendingReadings.length;k++) {
pendingReadings[k].synced = true;
}
});
The result should mark all readings synced true. However, it only marks alternative objects as synced (Maybe the previous write isn't complete when the request for next one comes in). What is the best way to update all entries in one go?
Realm's query results are live-updating. There are various way you could adjust your loop to account for that, but you would get the best performance by using the snapshot()
method on results instead...
let pendingReadings = database.objects('Readings')
.filtered('synced = false')
.snapshot();
database.write(() => {
for (let i = 0, len = pendingReadings.length; i < len; i++) {
pendingReadings[i].synced = true;
}
});
Also notice I adjusted the loop to only retrieve the length
once, which would slightly improve performance as well. You could use for...of
loops with Realm collections if you'd like, though there is a slight performance penalty in doing so compared to a "raw" loop like the one above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With