Having trouble displaying information on a Vue.js form retrieved from Cloud Firestore

I have implemented a contact form in my Vue.js template that utilizes v-model to display retrieved data within textfields. Within the script section, specifically inside the "created" block, I retrieve a document from Firestore using the provided docid.

After retrieving the document, I perform a check to ensure it is a valid object, and I can successfully output the found object to the console.

The issue arises when attempting to save the object retrieved from Firestore (referred to as the "applicant" object) to the pre-defined applicant object within the data block. While I am able to access and display the value of the doc's first_name property in the console (e.g.,

console.log(doc.data().applicant.first_name)
), I encounter difficulties binding it to this.applicant.first_name which should update the first name textfield accordingly.

An analysis of the error console indicates that I can output the data, but binding it to applicant.first_name poses a challenge.

https://i.sstatic.net/Nle0r.png

The code snippets are presented below for reference. (I suspect that this issue may be related to the execution of the code within the "created" block before the page is fully rendered.. however, I cannot confirm.)

Your help will be greatly appreciated!

Template

<template>
  <v-container
    fluid>
    <v-text-field v-model="applicant.first_name" label="First Name"/>
    <v-text-field v-model="applicant.middle_name" label="Middle Name"/>
    <v-text-field v-model="applicant.last_name" label="Last Name"/>
    <v-text-field v-model="applicant.email" label="Email"/>
  </v-container>
</template>

Script

<script>
  import db from '@/components/firebase/firebaseInit.js'

  export default {
    data() {
      return {
        applicant: {
          first_name: '',
          middle_name: '',
          last_name: '',
          email: ''
        },
      }
    created: function () {
      db.collection("applicants").doc(this.$route.params.id)
        .get()
        .then( function(doc) {
          console.log('Inside First call');

          if (doc.exists) {
            console.log("Document data:", doc.data())
            
            this.applicant.first_name = doc.data().first_name
            this.applicant.middle_name = doc.data().middle_name
            this.applicant.last_name = doc.data().last_name
            this.applicant.email = doc.data().email
          } else {
            console.log("No such document!");
          }
        })
        .catch(function(error) {
         console.log("Error getting document:", error);
        })

    }

  }
</script>

Answer №1

Hey, shoutout to @PolygonParrot for the solution! Included the let _this = this snippet and proceeded with setting the _this.applicant... values as shown below.

created: function () {
      let _this = this
      db.collection("applicants").doc(this.$route.params.id)
        .get()
        .then( function(doc) {
          console.log('Within the initial call');

          if (doc.exists) {
            console.log("Data from Document:", doc.data())
            

            _this.applicant.first_name = doc.data().first_name
            _this.applicant.middle_name = doc.data().middle_name
            _this.applicant.last_name = doc.data().last_name
            _this.applicant.email = doc.data().email
          } else {
          
            console.log("Document not found!");
          }
        })
        .catch(function(error) {
         console.log("Error fetching document:", error);
        })

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

Tips for customizing the IconButton appearance in material-ui

While Material-ui offers a default icon button, I am interested in customizing its design to resemble this: IconButton design needed Could you please advise me on how to make this change? Thank you. ...

Setting Javascript variables - listing elements

I have created a menu where I want to assign a variable to each li item and display an alert with its text when clicked. I managed to achieve this using the script provided below. $("ul#menudropd .animal li a").click(function() { var whatever = $(this ...

Guide to making a request in Node.js to Amazon S3 for downloading a specific file

Recently, I encountered an issue while trying to download a file from Amazon S3 using Node.js. Upon receiving the response, I noticed that there were 2 problems with the Buffer data: When I tried sending the buffer from Node.js to the frontend using res ...

Magnific Popup displaying only the initial item

As someone new to using jQuery and Magnific Popup, I am working on a grid of images. When an image is clicked, I want Magnific Popup to display a specific div containing information relevant to that particular image. <div class="grid"> <div c ...

Tips for extracting variables from a get OData call function

Is there a better approach to retrieving variables from a GET OData call? I'm struggling with extracting the 'id' variable from the call within my method. I've tried using callbacks, but have not been successful. Do you have any suggest ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

The useRouter() function doesn't seem to be successfully navigating to the main landing page

"use client" import { useState } from 'react'; import {auth} from '../../firebase-config' import {createUserWithEmailAndPassword} from 'firebase/auth' import { useRouter } from 'next/router'; const SignUp = ...

Executing functions from main component in tanstack table operations

One of the reusable React components I have is: "use client"; import { useState } from "react"; import { ColumnDef, flexRender, ColumnFiltersState, getFilteredRowModel, getCoreRowModel, getPaginationRowModel, ...

Using Javascript to change CSS in a Polymer application

Coming from a background in angular and react, I am now delving into the world of polymer. I have a polymer class called myClass with the following template. <div id="[[x]]"> Here, 'x' is a property defined in a property getter. stat ...

Unable to show JSON data on the console

I am attempting to retrieve a large array of JSON objects from a remote server. The server-side is based on Node.js + redis. Here is my ajax query: $.ajax({ crossDomain: true, type:"GET", contentType: "application/json", url: "http://****. ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

Simple methods to minimize the iteration of array loops in Node.js

First, retrieve the "grid_id" from the "grids" array ( Step 1 ) Next, verify if this "grid_id" is present in the "variationsDB" array ( Step 2 ) Once you have this "grid_id", use it to fetch the "var ...

How to Add Motion to Several Markers

Exploring the concept of moving markers on a map with drawn polylines to simulate simultaneous movement is a fascinating challenge. However, encountering some difficulties, such as only the last marker moving while the others remain stationary, can be frus ...

Incorporate an element id from a separate HTML document

Trying to extract the employee's name from march.html which has an ID like: <h3 id="name">John Doe</h3> I want to retrieve this name and display it in my index.php. This is for an 'Employee of the Month' feature where I need to ...

"Implement a feature that allows users to click on an image in a queue using

These are the images I have: <img src=img1.jpg class=pic /> <img src=img2.jpg class=pic /> <img src=img3.jpg class=pic /> <img src=img4.jpg class=pic /> <img src=img5.jpg class=pic /> <img src=img6.jpg class=pic /> .Sh ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

Bootstrap Datatable stops working when content is loaded through Ajax requests

While I understand that this question may seem like a duplicate, I have not been able to find a similar script to mine. As a newcomer to JavaScript and JQuery, transitioning from PHP, I'm struggling to navigate this terrain. Previously, my datatable ...

NodeJS - Assertion failure in callback function does not cause Mocha unit test to fail

I am currently facing an issue while running Mocha unit tests on a NodeJS application, specifically with handling assertions within callback functions. As an example, consider the following unit test: describe('PDF manipulation', () => { ...

Trigger a re-render of VueTable2 within the child component

My current setup involves a customer component that contains a child component with a vuetable 2. I am in need of a way to refresh the table whenever a new customer is created or updated in the parent component. I was considering using $emit on the parent ...

Leveraging the power of the underscore library within the WordPress

I'm currently utilizing the underscore library for handling arrays. I have included the library using the code snippet below in my functions.php file add_action( 'wp_enqueue_scripts', 'jt_enqueue_scripts' ); function jt_e ...