Max888
Max888

Reputation: 3780

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.

Upvotes: 3

Views: 1809

Answers (1)

dcts
dcts

Reputation: 1639

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'}"

Upvotes: 4

Related Questions