i have the following code
List<QueryDocumentSnapshot> localList2 = [] ; // inside list i have 5 docs
FirebaseFirestore.instance.runTransaction((transaction) async {
for (var element in localList2) {
DocumentReference userDoc= FirebaseFirestore.instance.collection("users").doc(element.get('userId'));
DocumentSnapshot chick = await transaction.get(userDoc);
if(chick.exists){
transaction.update(element.get('targetDocRef'),{
'fieldValue': 'value',
});
}
}
}).then((value){
log.log('done');
}).catchError((error){
log.log(error.toString());
});
when i run it i got the following error message
Transactions require all reads to be executed before all writes.
however i am not seeing any write task before read .
so i tried to use the whole transection into loop and this working fine but in my case i need it to chick result and write at once for whole docs .
how could i make it done ?
>Solution :
I think you might be misunderstanding the error message. It’s saying that all reads must happen before all writes. If there is more that one iteration of your loop, on the second iteration, the read for that iteration will happen after the first write. That means not all of your reads are happening before all of the writes.
Instead, have one loop that just reads all necessary documents, then after that, another loop that just writes all necessary documents.