Is it possible to access Firebase data in Vue.js, with or without Vuefire, using a router parameter before the DOM is rendered?

When I navigate to a view from another view, I pass the itemId as a param value to vue router.

My goal is to call firebase with that itemId in order to filter the data and use the filtered result/data in the UI. Specifically, I am utilizing vuefire.

The issue arises when Vue begins rendering before the data becomes available in the created() method, leading to an error in the console stating that the view refers to an undefined property values.

Is there a way to delay rendering the view until the data is accessible?

I have attempted using both beforeMount, created, and beforeCreate methods without success.

Here is the problematic code snippet:

<h1>{{projects[0].project_name}}</h1> //type error - cannot read property 'project_name' of undefined. It sometimes works on refresh but mostly does not.

Below is the script portion of the code:

    let projectsRef = db.ref('projects');
    export default {
        name: 'ProjectDetailsOpenInvesting',
        props: {
          data: Object
    },
    firebase:{
      projects: projectsRef
    },
    data(){
      return {
        projects:[],
        .....

      }
    },
    created(){
      var that = this;
      console.log(this.$route.params.itemid) //this works
      this.projects = this.projects.filter(function(p){
        return p.project_id == that.$route.params.itemid //this works as well
      })
    }

View Firebase screenshot here

Answer №1

One method you can use, as mentioned earlier, is to fetch data after navigation, meaning fetching the data in the component's created hook.

To achieve this with vuefire, you will need to bind the Realtime Database projectsRef Reference programmatically to the projects property in your Vue application, like so:

created(){
  console.log(this.$route.params.itemid)
  const itemId = this.$route.params.itemid;
  this.$rtdbBind('projects', projectsRef.orderByKey().equalTo(itemId)).then(projects => {
     this.projects === projects;
  });
}

As stated in the API documentation:

$rtdbBind returns a Promise that is resolved once the data has been retrieved and synced into the state.

Remember to install the rtdbPlugin plugin:


Additionally, instead of filtering the desired project item on the front-end (using

filter(function(p){return p.project_id == that.$route.params.itemid}))
), it is more efficient to filter it on the back-end at the database level (
projectsRef.orderByKey().equalTo(itemId)
). This approach avoids transmitting the entire set of objects from the back-end to the front-end, ultimately reducing costs associated with downloading unnecessary data. Refer to https://firebase.google.com/pricing?authuser=0 for more information.

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

Ways to retrieve the neighboring element's value and modify it with the help of JavaScript or jQuery

I am encountering a problem with selecting an adjacent element and updating its value. My goal is to update the input value by clicking the minus or plus buttons. I have successfully retrieved all the buttons and iterated through them, adding onclick eve ...

Encountering issues while attempting to execute node-sass using npm

Currently, I'm attempting to execute node-sass using npm. Displayed below is my package.json: { "name": "my-project", "version": "1.0.0", "description": "Website", "main": "index.js", "scripts": { "sass": "node-sass -w scss/ -o dist ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

I am puzzled by this error in Typescript: "Why does the element have an 'any' type when the Object type lacks an index signature?"

Looking to extract an array of keys from an object with nested properties, my current code: public static getKeys(obj: Object) { let keys: string[] = []; for (let k in obj) { if (typeof obj[k] == "Object" && obj[k] !== null) { ...

js.executeScript produces a Unexpected identifier error

Visit this link for proofs Running a script in the browser console on the specified page: let img = document.querySelector('.subscribe'), style = img.currentStyle || window.getComputedStyle(img, false), bi = style.backgroundImage.slice(4, -1).re ...

What is the recommended Vue js lifecycle method for initializing the materialize dropdown menu?

https://i.stack.imgur.com/cjGvh.png Upon examining the materialize documentation, it is evident that implementing this on a basic HTML file is straightforward: simply paste the HTML code into the body and add the JavaScript initializer within a script tag ...

Encountering issues with deploying Node.js app on GAE

My node.js app deployment to GAE is giving me trouble. The app is simple, connecting to Firebase to update a value. But every time I attempt to deploy, it fails. Works fine locally. I decided to start fresh, deleted my project, and deployed the default & ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...

AJAX: Building a Robust Single Page Application with Enhanced Security

Currently, I am developing a web/mobile application using AJAX. This app consists of 4 pages: the login page and three protected pages that are only accessible to logged-in users. My plan is to implement the Single Page Application pattern, where all 4 pa ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

Ways to prompt the debugger to pause whenever a specific script file is called during execution in Edge/Chrome debugger

I am currently in the process of debugging a Typescript web application, which is quite new to me as I have never delved into web development before. This particular project entails multiple script files and various libraries. While running the applicatio ...

I require displaying the initial three letters of the term "basketball" and then adding dots

Just starting out with CSS and struggling with the flex property. Seems to work fine at larger sizes, but when I reduce the screen size to 320px, I run into issues... Can anyone help me display only the first three letters of "basketball ...

Invisible Thinglink image revealed upon resizing browser

I am currently repurposing a pre-existing theme that has a drop-down menu showcasing an image. I am attempting to integrate a Thinglink into the content section of this drop-down, but unfortunately, the image does not appear until I adjust the size of the ...

What is the proper way to utilize the toISOString() function in JavaScript?

My current code uses currentDate.toISOString() to output the date in this format: "2013-01-15T12:08:54.135Z". However, I actually need the date to be formatted like this: "2013-01-15T12:08:54-06:00". The "-06:00" represents the timezone. ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

Most effective method for structuring a JSON format that contains recurring keys for every item within its array

Currently, I'm creating a JSON object that includes multiple addresses. My main concern is the potential for the JSON size to grow too large, which could impact browser performance and parsing speed in JavaScript. Each address includes keys such as "I ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

How can I duplicate or extract all the formatting applied to a specific text selection in Ckeditor?

I am currently utilizing CKEditor version 3.6 within my Asp.net MVC 3 Application. One of my tasks involves creating a Paint format option similar to Google Docs. I am looking to integrate this feature into CKEditor. Is there a way in CKEditor to transfe ...

Launching a bootstrap modal within another modal

I am facing a minor issue with two modal popups on my website. The first modal is for the sign-in form and the second one is for the forgot password form. Whenever someone clicks on the "forgot password" option, the current modal closes and the forgot pas ...