0

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?

2
  • Try using set instead of update Commented Jan 21, 2021 at 13:49
  • It doesn't work with set Commented Jan 22, 2021 at 7:39

1 Answer 1

0

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().

Sign up to request clarification or add additional context in comments.

6 Comments

We basically do the same thing, you create a black document, while I write a new one. I believe the problem is that since documentReference.id is a runtime variable, when I start the app again and it makes the request automatically the value is null in that point of time. Is there any way around this?
The answer lies in the middle actually. I should create a document reference but without an await method and then set the document with that id again without await, since I need every other function just like above to cache. Then when the user finds internet again the functions are being called. The main problem was in the use of await.
The await in my first snippet is indeed not needed; I removed it. The more important thing about my answer is that a doc() call without any arguments does not actually create a document in the database, but merely a reference. Only the call to set() creates the document.
@user14624595 Did you make any progress here?
Done. Good to hear you got it working. 👍
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.