Ways to generate data following the integration of Firebase Firestore in Vue.JS

How can I display the orders data retrieved from Firebase in my browser console? See the image link below for reference.

This is the code snippet for fetching data from Firebase and displaying it in the console:

orders(){
    const db = firebase.firestore();
    const dbOrderRef = db.collection('order');
    dbOrderRef.get()
        .then(res => {
            res.forEach(doc => {
                console.log(doc.data())
            })
        })
        .catch(err => {
            console.log('error', err)
        })
}

I attempted to store the data in an instance variable like so:

ordersData = []

and then assign it in a method:

this.ordersData = doc.data()

However, this did not work as expected. Any suggestions on how to achieve this goal?

Thank you

Answer №1

To clarify your question, it seems like you are looking to populate an array named ordersData with orders retrieved from a Firestore query.

You can achieve this by using the following code snippet:

const db = firebase.firestore();
const dbOrderRef = db.collection('order');

let orderArray = [];
dbOrderRef.get()
    .then(res => {
        res.forEach(doc => {
            let orderObj = doc.data();
            orderObj.id = doc.id;
            orderArray.push(orderObj);
        });
        this.ordersData = orderArray;
    })
    .catch(err => {
        console.log('error', err)
    })

Subsequently, you can render the ordersData array within your template as shown below:

            <div v-if="ordersData.length">
                <div v-for="order in ordersData">
                    <h5>{{ order.name }}</h5>
                    <p>Price: {{ order.price }}</p>
                    <p>
                     <a @click="openOrderDetail(order.id)">Open order</a>  
                     // This demonstrates how to invoke the openOrderDetail() method with the Firestore document id of the order.
                     // By doing so, you can potentially navigate to a page where you retrieve detailed information about the order based on its id.
                    </p>
                </div>
            </div>

Answer №2

When utilizing the then method, the keyword used inside the block pertains to the block itself rather than the Vue object. To handle this, we can create a workaround by saving the Vue reference in another variable and accessing the necessary data using that variable.

let _self = this;
const db = firebase.firestore();
const dbOrderRef = db.collection('order');
dbOrderRef.get()
    .then(response => {
        response.forEach(document => {
            _self.ordersData = document.data();
            console.log(_self.ordersData);
        })
    })
    .catch(error => {
        console.log('error', 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

Utilizing React JS to dynamically adjust the z-index upon clicking a component

My goal is to create a functionality where clicking on a box will move it to the top, with the previous box now underneath. For a better understanding, please refer to the following code snippet. https://codesandbox.io/s/optimistic-payne-4644yf?file=/src/ ...

Attempting to start and restart an asynchronous function using setIntervalAsync results in a TypeError because undefined or null cannot be converted to an

Recently, I've been working on creating a web scraper that utilizes data extracted from MongoDB to generate an array of URLs for periodic scraping using puppeteer. My goal is to make the scraper function run periodically with the help of setIntervalAs ...

In Javascript, navigate to a specific section by scrolling down

Currently, I am in the process of enhancing my portfolio website. My goal is to incorporate a CSS class once the user scrolls to a specific section on the page. (I plan to achieve this using a JavaScript event). One approach I am considering is initially ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Sending Data as a Response in Vue Component

I have successfully called the axios and displayed the response using console log. However, I am now trying to pass the axios post response value to my Vue component so that I can display the response within the component in order to use it for a condition ...

Python code allowing users to navigate back to the previous page while retaining elements

After my script scrapes the page, it automatically clicks a button if a new element meeting certain criteria is found. Everything works perfectly when there is only one element, but an issue arises when the button click leads to a new page opening. If ther ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Managing field placement as the table height grows: tips and tricks

I am encountering an issue with my dynamic form. When I click on the add button, a new row is added to the table. However, once there are more than 6 rows added, the table height starts covering the fields. How can I go about setting this so that the field ...

Tips for displaying a dropdown on top of a modal with the help of Tailwind CSS

I am currently utilizing Tailwind CSS and I am struggling to display the white dropdown over my modal. Despite attempting to use the z-index, I have been unsuccessful in getting it to work. Do you have any suggestions or insights on how to resolve this is ...

Django and VueJS: Error 403 - Forbidden request due to missing or incorrect CSRF token

My tech stack includes Django and Django REST framework on the backend, along with Vue.js on the frontend. While GET requests function smoothly and POST requests using Postman or Insomnia work fine, encountering an error in the Browser console when sending ...

In order to achieve a sliding effect for the second div, it can be programmed to

Currently, I am working on implementing hide and show functionality in my project. However, I have come across a bug in my code that I need assistance with. When clicking on the first div element, the content opens from bottom to top instead of the desired ...

Tips on sending an array to material-ui dataSource props

Currently utilizing material-ui for a component. I am facing an issue with the autocomplete component in material-ui where I intend to display a list of icon names along with the icons. When only passing MenuItem to dataSource, it results in an empty input ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

Passing parameters to Next.js pages

Here is my function: export async function getServerSideProps({ req }: any) { const user = ( await axios.get("http://localhost:4000/api/auth/status", { withCredentials: true, headers: { Cookie: `connect.sid=${req.cookies["c ...

jQuery wrapAll issue

I have a repeating group of three divs in my code that I need to wrap together. Here's an example from my HTML: <div class="one" /> <div class="two" /> <div class="three" /> <div class="one" /> <div class="two" /> <d ...

The comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

Simple yet perplexing JavaScript within an Angular directive

In the tutorial, the author explains that each element in the stars array contains an object with a 'filled' value, which is determined as true or false based on the scope.ratingValue received from the DOM. directive('fundooRating', fu ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

Is there a way to modify my code to restrict users from liking a post multiple times?

I am currently working on a like system and I have made some progress. However, I am struggling to make it so that the likes only increment once. Does anyone have any insights or suggestions on how to achieve this? I have considered using session variables ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...