0
votes

I have an app that uses firestore, when the user clicks a button I add a document, in which after its creation, I also add its documentId in a field , which is an alphanumeric string generated by firestore. My problem is that if a user clicks the button without internet, then closes the app and opens it with an internet connection the document gets created, but of course its Id inside it is null, since the programm stopped executing. Is there a way I can persist that?

for example

DocumentReference documentReference =
      await FirebaseFirestore.instance.collection('sth').add(map); //map has a 'docId' key

 await FirebaseFirestore.instance
  .collection('sth')
  .doc('${documentReference.id}')
  .update({'docId': documentReference.id});

The update one does not have offline persistence, is there any way around it?

1
Try using set instead of updateDima Rostopira
It doesn't work with setuser14624595

1 Answers

0
votes

As Dima commented, you can solve this by first generating the ID, and only then writing the document with both the data and its ID.

To generate a document ID without writing to it, you can call doc() on the CollectionReference without an argument.

DocumentReference documentReference =
     FirebaseFirestore.instance.collection('sth').doc();

map["docId"] = documentReference.id;

FirebaseFirestore.instance
  .collection('sth')
  .doc('${documentReference.id}')
  .set(map);

Now the first line is a pure client-side operation, without any data being written to the database yet - so you end up with a single, atomic write/set().