Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to include loop inside transection

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading