Waiting for update completion in Firebase Firestore (Javascript for web development)

When I retrieve a document, update it, and then try to access the updated data, I am getting undefined logged. Can anyone explain why this is happening and suggest a solution for successfully fetching the new data from the document?

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

I am working with the JavaScript Web version of Firebase.

Answer №1

It seems like you are looking to ensure that the update process is completed before proceeding with the code execution. When you call update on a DocumentReference, it returns a promise that resolves to a WriteResult. You can simply await for this promise to resolve before moving forward with the rest of the code:

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

// Update the document and wait for completion
docRef.update({ message: "hello" }).then(writeResult => {

  // Wait for update to complete before displaying WriteResult
  console.log(writeResult);

  // To confirm that the update is done, fetch the same document from Firestore
  return docRef.get();

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

SAME APPROACH USING ASYNC/AWAIT SYNTAX

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

// Update the document, wait for completion, and display write result
const writeResult = await docRef.update({ message: "hello" });
console.log(writeResult);

// Confirm update completion by fetching the updated document from Firestore
const documentSnapshot = await docRef.get();
console.log(documentSnapshot.id, "=>", documentSnapshot.data()); 
// => "docid => { message: 'hello'}"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Upon completing the npm install process, the error message 'getFirebase() is not a function' was displayed

I've been working on a small react app and making good progress, but I still feel like I have a lot to learn. Recently, I encountered a problem that has me stumped. Everything was fine in my code until I opened another app in Visual Studio and it wasn ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

Implementing conditional visibility toggling in React

I am experiencing an issue where I am attempting to change a div's visibility from hidden to visible upon button click. Despite clicking the button, the visibility of the div does not change as expected. Upon inspecting the console after executing the ...

Error message: The function for the AJAX call is not defined

I'm currently working with jQuery's ajax function and encountering an error: 'getQty is not defined' Can you spot my mistake here? jQuery Code: function getQty() { var dataString = "itemId=" +$(".itemId").val(); $.ajax({ t ...

What are the steps to implement the "render" function from one class into another class within three.js?

As a newcomer to three.js, I have been working on creating a bowling game. However, I am encountering an issue where I need to access a function from my "Application" class within the physics class that I have created. Here is a snippet of the Application ...

The calculator is experiencing issues with JavaScript functionality

Having some trouble developing a calculator using HTML5, CSS, and JavaScript. After passing my HTML and CSS through validators successfully, I encountered issues when adding JavaScript functions to enable the functionality of the buttons on the calculator. ...

Converting a numerical value starting with zero into a string while retaining the leading zero

I am facing an issue with my JavaScript code that retrieves GPS location from a browser. Due to the limitation of writing coordinates to an SQL database directly from JavaScript, I have resorted to sending it via PHP by utilizing the controller "site" and ...

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

What steps are involved in implementing Local fonts in theme UI for Next JS?

I am currently developing an application using next JS with [theme-UI][1]. However, I need to implement local or custom fonts in my project and I'm unsure of how to do this. Below is the current theming setup: const theme = { fonts: { ...

Is it permissible to use multiple JWT tokens in the HTTP header?

Currently, I have implemented the jwt access and refresh token pattern for client-server communication. The method involves sending two jwt tokens in the header: the access token and the refresh token. This is done by adding the following code to the heade ...

The POST request made using Postman shows an empty Node.js/Express req.body

Here is the current code snippet I am working with: var express = require('express'); var router = express.Router(); var db = require('../helpers/db'); var data = { "1": 127, "2": 236, "3": 348 } router.get('/', ...

Tips for preloading a script in nextjs

I'm having trouble incorporating a script into my website. The issue is that the script doesn't load properly the first time the page loads, but after a few refreshes, it works and the responsible iFrame shows up. I've attempted several di ...

I often find that jscodeshift consistently avoids processing my JavaScript files

I am currently in the process of updating my react application to the newest version of Material-UI. I came across a migration helper script using jscodeshift within the material UI project. (https://github.com/mui-org/material-ui/tree/master/packages/mate ...

What is the process of adding files to my Svelte / Sapper server build using __sapper__?

Currently, I am working on integrating a server middleware called Parse into my sapper server configuration located in sapper-project/src/server.js. express().use('/api', const api = new ParseServer({ databaseURI: 'mongodb://localhost:27 ...

Can you explain the distinction between compiled and interpreted programming languages?

Despite my efforts to research the topic, I am still confused about the distinction between a compiled language and an interpreted language. It has been mentioned that this is one of the distinguishing factors between Java and JavaScript. Can someone ple ...

Issues with passing parameters in JavaScript

I am facing an issue while passing multiple variables from a PHP page to a JavaScript function. Only the first parameter seems to be passed successfully. In the PHP code, the script is being called like this: <? $sdate = 0; $edate = 2; ?> <scrip ...

Changing the value of a JavaScript variable within the .Net Codebehind

I've run into an issue where I need to update a JavaScript variable after post-back. My initial approach was to use the ClientScript.RegisterStartupScript function, which worked fine during the first page load but failed on subsequent postbacks. I inc ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

An unanticipated SyntaxError was encountered while attempting to utilize an Ajax post, specifically in relation

I can't seem to figure out how to troubleshoot an ajax/jquery error. Here is the function I'm working with: var LogIn = { Email: $("#Name").val(), MobileNo: $("#txtMobileNumber").val(), PinCode: '', ...

Looking for a way to efficiently add multiple value inputs to a JSON object using jQuery or JavaScript?

Here is the HTML input tag code I am working with: <form id="info"> <input id="A" name="A" type="hidden" nodetye="parent" value="A"> <input id="A1" name="A1" type="text" nodetype="child" value="a1val"> <input id="A2" name ...