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 troubleshoot and resolve the jQuery error with the message "TypeError: 'click' called"

I am currently developing a project for managing Minecraft servers, focusing on a configuration panel. I have set up a form that users need to fill out in order to configure the settings and send the values using Ajax. However, I encountered an error: Type ...

Is there a way to modify the text within a "span" element that directly follows an "i" element using jQuery?

I am attempting to modify the text displayed on a button within a plugin by using jQuery. Here is the outer HTML: <button value="[[3,1,1488182400]]" data-group="2017-02-27" class="ab-hour"> <span class="ladda-label"> <i class="ab-hour ...

When I try to hover my mouse over the element for the first time, the style.cursor of 'hand' is not functioning as expected

Just delving into the world of programming, I recently attempted to change the cursor style to hand during the onmouseover event. Oddly enough, upon the initial page load, the border style changed as intended but the cursor style remained unaffected. It wa ...

Tips for changing the content of a td element to an input field and removing the displayed value

I am facing an issue with a dynamic table that displays names and input fields. When a name is displayed in a table row, the user has the option to delete that name. I am able to remove the value from a specific table row, but I am struggling to replace th ...

Preventing dragging in Vis.js nodes after a double click: a definitive guide

Working with my Vis.js network, I have set up an event listener to capture double clicks on a node. ISSUE: After double-clicking a node, it unexpectedly starts dragging and remains attached to the mouse cursor until clicked again. How can I prevent this b ...

What advantages does $sce or Strict Contextual Escaping provide in AngularJS, and why is it unnecessary for React?

I find it perplexing that I am unable to fully grasp the true value of utilizing SCE in AngularJS (even after reviewing the documentation) when it comes to security benefits. It leaves me wondering why React does not require SCE. So, to summarize my quest ...

Implementing tooltips using JavaScript within Bootstrap 5

Is there a way to add both a tooltip and popover to the same element in Bootstrap v5 via Javascript? I have attempted to enable both of them using JS as it seems like the best approach. The tooltip that was added through html is functioning correctly: ...

Working with JSON data in javascript

While trying to parse JSON data from a server, I came across a strange issue. The data consists of rows of data - essentially a list of lists - and it looks something like this: [[1,2,3],[4,5,6],[7,8,9]] When viewing the JSON data in FF (using Firebug), ...

What is the most efficient way to transform an array of objects into a compact string?

I'm exploring a new project with an import/export feature in mind. Initially, I will have an array containing approximately 45 simple objects structured like this: {"id": "someId", "quantity": 3} To make it exportable, t ...

transmit JSON data with an AJAX request and receive a response

I'm looking to make a JSON request to an API and receive a response. I tested it using Postman and successfully received the following response: JSON request to API: { "apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp" } The response I receiv ...

"Patience is key as you wait for various pictures to fully

I have a collection of images to load, all organized in an Array. As each image is loaded, I increase a counter within a loop. Once this counter matches the length of my images Array, I intend to remove the loading indicator. For some reason, it's ...

Automated browsing: identifying the difference between AJAX and iframes

During my automated requests (scheduled at specific times, without user involvement), I have noticed that xmlHttpRequest includes extra http headers. In order for the server not to be able to distinguish these requests as automated (they should appear exa ...

Tips for retaining a chosen selection in a dropdown box using AngularJS

How can I store the selected color value from a dropdown box into the $scope.color variable? Index.html: <label class="item item-select" name="selectName"> <span class="input-label">Choose your favorite color:</span> <select id="colo ...

The next.js application utilizing a custom server is experiencing rendering issues

Expanding my knowledge to next.js, I might be overlooking a simple aspect. My goal is to implement custom routes, so I crafted a server.js file and adjusted the command in my package.json to node server.js. Below is the entirety of the server.js file: con ...

Form featuring two buttons with distinct values for submitting

<form action="here.php" method="POST"> <input type="text" name="text"> <div id="one"> <input type="hidden" name="aaa" value="one"> <input type="submit" value="Send"> </div> <div id="two"> <input type= ...

Want to easily switch between pictures in the Gallery?

I've created a gallery using jQuery, CSS & HTML and now I want to implement next and previous image buttons. I have added the buttons to the page and written functions for them, but I am struggling with the implementation. Here is my code, if anyone h ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...

Is it advisable to utilize media queries and transform: translateY(-%) to position content above the mobile keyboard?

I've been struggling for nearly a whole day and could really use some assistance. I'm having trouble understanding how chat web apps manage to work around this particular issue. There have been numerous forum posts discussing the problem: I am tr ...

Issues with the functionality of the submit button (html, js, php)

Seeking assistance with a submit button functionality issue - I have a simple submit button that allows visitors to enter their email address. Upon clicking the button, it should add their email to a CSV file and display a pop-up thank you message. The pr ...

What could be preventing the webpack dev server from launching my express server?

Currently working on a straightforward web application using express and react. The front-end React bundle is being served via the express server. Everything runs smoothly with my start script, which builds the front-end code and launches the express serv ...