Binding Vue data with Firestore

I am looking to extract information from a firestore database and link it to the vue data.

To retrieve data from firestore, I use the following method within the created lifecycle hook:

  created(){

console.log(firebase.auth().currentUser);
const docRef = firebase.firestore().collection("users").doc("VezLOaumLCza8jih8Ylk");
docRef.get().then(
  function(doc){
    if(doc.exists){
      console.log(`Document data: ${doc.data()}`);
      this.user = doc.data();
    } else {
      console.log(`Doc data is undefined`);
    }
  }).catch(function(err){
    console.log(`Oops: ${err.message}`);
  });
}

The problem arises when this does not point to the vue instance; in fact, it is undefined at the moment I try to assign the user variable. How can I connect the user data to the vue data? It seems like I am overlooking something, but I cannot identify what might be causing the issue.

The end goal is to create a form that allows users to edit their own data.

(the expected results are obtained when printing out the doc.data())

Answer №1

When the then callback is a separate function, accessing this inside that function refers to the then callback itself. To avoid this issue, it is recommended to establish a reference to the Vue instance before entering the then callback.

Consider the following approach:

created(){
  
  console.log(firebase.auth().currentUser);
  const docRef = firebase.firestore().collection("users").doc("VezLOaumLCza8jih8Ylk");
  var vm = this; // Creating a reference to the Vue instance.
  docRef.get().then(
    function(doc){
      if(doc.exists){
        console.log(`Document data: ${doc.data()}`);
        vm.user = doc.data();
      } else {
        console.log(`Doc data is undefined`);
      }
    }).catch(function(err){
      console.log(`Oops: ${err.message}`);
    });
}

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

What is the answer to this issue where the entity name is required to directly come after the "&" in the entity reference?

Whenever I insert the code into my Blogger platform, an error pops up stating: The entity name must directly follow the '&' in the entity reference Here is the code: <script> if (typeof bc_blocks == "undefined" && wind ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

What is the best way to use the copy files npm module to recursively copy all images from a source folder to a destination folder?

Is there a way to use the copy files command to transfer images (.png, .jpg) from an "src" folder to a "dist" folder while retaining the same filepaths internally and also ensuring it works recursively? https://www.npmjs.com/package/copyfiles I am curren ...

Utilize SWR to retrieve data that corresponds to the chosen value from the dropdown menu

Can SWR fetch data based on the selected value in a dropdown? Initially, it works, but when I select a previously selected value, it doesn't fetch the correct data. Using the Fetch API const { data: entities } = useSWR( currentEntity?.enti ...

Issue with Custom Directive: Receiving Token Error for Expression in Isolated Scope in Angular

(The following messages, code snippets, etc, have been slightly altered for clarification) The error message received is as follows: Syntax Error: Token 'promiseObject' is unexpected, expecting [:] at column 3 of the expression [{{promiseObject ...

How can I implement sending FCM Push Notifications at a 3-hour interval using Node.js?

I'm facing a challenge in sending push notifications to users who were active on our platform yesterday. I want to send these notifications once every morning, but I'm struggling with creating an automated process that sends messages every 4 hour ...

Express server unable to connect to schema table causing error

I've been working on setting up a backend express API for displaying contact details on a contacts us page and saving form details to my database. Unfortunately, I keep encountering error status 500 with the message "error saving data: error: relation ...

Failure of AJAX Callback Triggering

Behold, behold! Witness the mighty ajax function: function ajax_call(call_method,data_to_send) { logger("Journey with me through the lands of ajax_call. Lo and behold, the data_to_send: "); logger(data_to_send); $('.clickable save_button& ...

Loading items into multiple containers using PHP AJAX pagination

I'm looking to implement a "load more" button on my website, but I'm facing a challenge due to my three-column layout. I want to load more items into their respective parent elements without disrupting the design. While I've used infinite aj ...

What is preventing me from filling my array with the URL inputted by the user?

I am looking to dynamically populate an array with URLs and display them one by one as users upload files. The goal is for each user to upload a file, have it stored in the array, and then displayed on the page. Specifically, I want to generate <img/&g ...

javascript variable pointing to an unknown object

Below is the essential code snippet to consider: JS function ToggleRow(objTwistie, objRow) { if (objRow.style.display == "none") { objRow.style.display = ""; objTwistie.src = "../Images/SectionDown.gif"; } else { objRow.style.display = "n ...

How can I make my webpage unselectable except for specific content within a div using CSS and JavaScript?

During a live editing session, I am looking to make only specific portions of the page selectable. Can someone provide guidance on how to disable selection for everything except within a particular div? ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Is there a way for me to send a form containing pre-existing data from a different page?

Seeking advice: I realize that utilizing jQuery's ajax function may be the simplest approach, however I am facing an issue with the form field names. The var_dump below displays the typical values submitted by the form using test data. It appears that ...

Generating a constantly evolving 3D model and keeping it current within a web browser

My website already has a large user base, and I am looking to create a 3D visual representation of data on one of the pages. This model needs to be easily updatable based on each user's database information (imagine a square board with a ball whose po ...

"Bootstrap's modal-backdrop element presents a striking fade effect as it

Issue I am facing a problem related to Bootstrap, specifically with a modal in my HTML file. Whenever I call the modal, it appears with a fade-in effect. The code for my modal: <div class="modal fade" id="exampleModal" tabindex=& ...

Duplicate object omitting certain fields

I am faced with the challenge of working with two interfaces: public interface ObjectOne { field1: string; field2: string; field3: string; field4: string; field5: string; ... } public interface ObjectTwo { field2: string; field5 ...

Are you utilizing content loaded through jquery load in your work?

I have successfully utilized jQuery's .load() function to retrieve the contents of a table from another webpage and insert it into the current page, which is functioning properly. However, when I try to run scripts afterwards that manipulate the newly ...

Modify the component's background color when hovering

Is there a way I can modify the background color of the entire panel on hover? I am currently using a simple bootstrap panel with bootstrap-react: <LinkWrapper url={url}> <Panel header="text" bsStyle="primary"> <p>text.</p> ...

The Controller of Conversations

In the HTML code, there is a dialog element with an identification of divMyDialog1. This dialog is connected to a JavaScript class called MyDialog1. Each dialog has its own unique id and associated class name. MyDialog1 = function(divStr){ this.divStr ...