Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore wait for update to complete (js web)

In the below I get a doc, update it, then try to use the data from the update, however undefined is logged. Why is this and how can wait to successfully fetch the new data from the doc.

db.collection("collection").doc("docid").get().then(doc =>
  doc.ref.update({ message: "hello" }).then(() => console.log(doc.data().message));
)

I am using the Javascript Web version for firebase.

like image 558
Max888 Avatar asked Nov 28 '25 23:11

Max888


1 Answers

if I understood correctly, you want to wait for the update to complete before continuing with the code. Calling update on a DocumentReference returns a promise that resolves to a WriteResult. You could simply wait for the promise to resolve and then continue with the code:

// store DocumentReference
const docRef = db.collection("collection").doc("docid");

// update document
docRef.update({ message: "hello" }).then(writeResult => {

  // wait for update to complete and display WriteResult
  console.log(writeResult);

  // to prove that update is finished, fetch the same document from firestore
  return docRef.get();

}).then(documentSnapshot => {
  console.log(documentSnapshot.id, "=>", documentSnapshot.data()); 
  // => "docid => { message: 'hello'}"
})

SAME SOLUTION WITH ASYNC AWAIT SYNTAX

// store DocumentReference
const docRef = db.collection("collection").doc("docid");

// update document + wait for completing, then display write result
const writeResult = await docRef.update({ message: "hello" });
console.log(writeResult);

// to prove that update is finished, fetch the same document from firestore
// and display document content
const documentSnapshot = await docRef.get();
console.log(documentSnapshot.id, "=>", documentSnapshot.data()); 
// => "docid => { message: 'hello'}"
like image 99
dcts Avatar answered Nov 30 '25 13:11

dcts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!