Unable to postpone the utilization of data in Vue until after retrieving the value from the database

I am facing an issue where I need to compare a string obtained from Firebase in document.check1 with specific strings (hardcoded in the function below) and display content accordingly. Currently, I know how to trigger this comparison on button click, but I want it to happen automatically as soon as the page loads, without requiring user interaction. However, when I attempt to do so, I encounter an error indicating that the value is null. How can I make it wait for the data to be fetched automatically?

 <template>
         <router-link to="/konto">Back</router-link>
         <div v-if="document">        
           <div>
             <span>1:</span>
             {{ document.check1 }},
             <span>2:</span>
             {{ document.check2 }},
             <span>3:</span>
             {{ document.check3.length }}
           </div>
         </div>
         <button v-if="itWorkOk" @click="documentCheck">Show Content after finding result</button>
          <div v-if="isOther">
           <p>Content</p>
         </div>
 </template>
 
 <script>
 import getUser from "../composables/getUser";
 import getDocument from "../composables/getDocument";
 import { ref } from "@vue/reactivity";
 
 export default {
   props: ["id", "document"],
   setup(props) {
     const { error, document } = getDocument("AllData", props.id);
     const { user } = getUser();
 
     const itWorkOk = ref(true);
     const result1 = ref("");
     const isOther = ref("");
 
     const documentCheck = async () => {
       const isItOk = document.value.check1
       if (isItOk == "Result One") {
         result1.value = true;
         itWorkOk.value = false;
       } else {
         isOther.value = true; 
         itWorkOk.value = false; 
       }
     };
 
     return {
       error, user, document, documentCheck, result1, isOther, itWorkOk,
     };
   },
 };
 </script>

The error (when I put function to call immediately):

Uncaught (in promise) TypeError: document.value is null

The getDocument code:

import { ref, watchEffect } from 'vue'
import { projectFirestore } from '../firebase/config'

const getDocument = (collection, id) => {

  const document = ref(null)
  const error = ref(null)

  let documentRef = projectFirestore.collection(collection).doc(id)

  const unsub = documentRef.onSnapshot(doc => {
    if(doc.data()) {
        document.value = {...doc.data(), id: doc.id}
        error.value = null
    } else {
        error.value = "Document does not exist"
    }
    
  }, err => {
    console.log(err.message)
    error.value = 'Couldn't get the document'
  })

  watchEffect((onInvalidate) => {
    onInvalidate(() => unsub());
  });

  return { error, document }
}

export default getDocument

Answer №1

To properly address your inquiry, it seems you are looking to retrieve Firestore data within a specific lifecycle hook of a Vue component, such as created or mounted.

Within this lifecycle hook, you can asynchronously fetch the data from Firestore and then compare it with the expected values.

Answer №2

After exploring various options, I ended up implementing a solution using setTimeout(function () { methotToCall(); }, 1000) as suggested in this helpful thread on stackoverflow.com. It may not be the most ideal method, but it did the job for now. Many thanks for the assistance!

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

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

What could be causing the $httpProvider.interceptors to unexpectedly return an 'undefined' value?

Having some trouble parsing the response of my basic AngularJS app that consumes Yelp's API using $httpProvider.interceptors. This is the structure of my app: var app = angular.module("restaurantList", []); The yelpAPI service handles authenticatio ...

Bring in content using transclusion, then swap it out using AngularJS

I am looking to develop a custom directive that will transform : <my-overlay class="someOverlay"> <h4>Coucouc</h4> </my-map-overlay> Into : <div class="someOverlay default-overlay"> <h4>Coucouc</h4&g ...

Algorithm for detecting collisions in Javascript

I am looking to implement a collision detection function in JavaScript for canvas. Specifically, I have coin and piggy bank objects and want to create a function that triggers the disappearance of a coin object when it comes into contact with a piggy bank. ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

Is it advisable to compress my API response in PHP?

At this stage, I find myself needing to generate extensive reports in order to gain a better understanding of the data at hand. To do so, I must retrieve one of my tables which contains around 50 parameters and 40,000 rows. While fetching the data via API ...

Rendering a page for a missing resource

Within the App.js file, the routes component is currently only wrapping a portion of the website. However, I would like the NotFound component to be rendered for the entire page if an incorrect URL is entered. Can you please provide guidance on how this ...

What is the best method for rounding a decimal number to two decimal places?

Here is the JavaScript code I am using: $("input[name='AuthorizedAmount'], input[name='LessLaborToDate']").change(function () { var sum = parseFloat($("input[name='AuthorizedAmount']").val()).toFixed( ...

"Frustrating issue with Firebase-admin dependency farmhash-modern resulting in webassembly error

Facing an issue while setting up firebase-admin SDK on my nextjs + TS project. Every time I try to call a SDK function, I encounter a webAssembly error. Specifically, when trying to configure a middleware for the server-side API and calling the verifyIdTok ...

Combining cells through the utilization of JavaScript

I've searched for ways to merge cells in a table using JavaScript but haven't been able to find any code that works. Is there a specific approach I can follow to implement cell merging like in MS-WORD tables? Your advice would be greatly apprec ...

The art of finding information algorithm

Having a JSON file containing about 10,000 records, each record includes a timestamp in the format '2011-04-29'. Currently, I also have a client-side array (referred to as our calendar) with arrays such as - ['2011-04-26', '2011- ...

Having trouble establishing a connection with the socket.io server on the local network

After successfully setting up communication between my nodeJS server and a vueJS app via socket.io on my main computer, I encountered a challenge. While running my node server and vue app in dev mode, the socket connection works when I access the app throu ...

What steps should I follow to properly set up my tsconfig.json in order to ensure that only the essential files are included when executing npm run build

Introduction I am seeking guidance on how to correctly set up my tsconfig.json file to ensure only the necessary files are included when running npm run build for my projects. I want to avoid any unnecessary files being imported. Query What steps should ...

Prevent JSON.parse() function from stripping away any trailing zeros in a JSON string dataset

After creating a JSON string, I encountered an issue where the values were not being parsed correctly. Here is the code snippet: <script> var string = JSON.parse('{"items":[{"data":[5.1]}, {"values":[5.10]}, {"offer":[3.100]}, {"grandtotal":[12 ...

Issue: AngularJS modal not appearing when utilizing partial for template URLExplanation: The Angular

I am having trouble with a modal in a partial file that is supposed to be loaded into my main view using an ng-include tag. However, the template cannot be found and I do not see it being loaded in the console or network tab. The error message I receive is ...

The modal form vanishes without any action when the form is clicked outside

Everything was working fine with the form submission until I turned it into a modal using Bootstrap. Now, when the form is rendered in the modal, users can tab and type without any issues. However, if they click on any element within the modal (including t ...

How to selectively disable buttons in a group using React

I am working with an array of data const projectTypeValues = [ { name: 'Hour', value: 'hour'}, { name: 'Day', value: 'day'}, { name: 'Session', value: 'session'}, { name: 'project', valu ...

Encountering the 404 Not Found error when trying to fetch the Next.js API Route from the app

Currently facing difficulties with the routing in Next.js 13's app. Every time I attempt to access it, for instance via Postman, I keep getting a 404 Not Found error. This is my file structure: https://i.stack.imgur.com/ZWrlb.png An example of one ...

The Jquery animate function is not compatible with the transform property

I am facing an issue with the Jquery animate function. Despite trying various solutions, I have been unable to get it to work. Below is the HTML code that I have used: <!DOCTYPE html> <html lang="en"> <head> <meta cha ...