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.

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

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

What makes using setInterval with a self-invoking function a smarter choice?

I recently came across an explanation on how to properly use the setInterval() function. Essentially, it was mentioned that (function(){ // perform some actions setTimeout(arguments.callee, 60000); })(); ensures that the subsequent call from setTim ...

Tips on creating a hierarchical ul list from a one-dimensional array of objects

I have an array filled with various objects: const data = [ {id: "0"},{id: "1"},{id: "2"},{id: "00"},{id: "01"},{id: "02"},{id: "11"},{id: "20"},{id: "23"},{id: & ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

What is the best method to iterate through a jQuery array variable without any errors?

I am struggling with a PHP project where I need to create a json array of data values that will be used in a jQuery script. The array looks something like this: [3,94,83,141]. My goal is to leverage these values to manipulate the visibility of rows in a ta ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

Certain cases will see success with iPhone jquery/ajax functionality, while others may encounter

I am facing an issue with multiple pages in my project that utilize AJAX to submit a form to django. While the buttons work perfectly on various platforms and browsers like Chrome, Firefox, and desktop Safari, they seem to malfunction specifically on mobil ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

How can you update the background image of a particular div using the 'onclick' feature in React.JS?

Thank you for helping me out here. I'm currently working with ReactJS and facing a challenge where I need to change the background of a div from a color to a specific image URL upon clicking a button in a modal. Despite my efforts, I keep encountering ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

Express application receiving repetitive post requests

Recently, I have been working on developing a YouTube video conversion app that utilizes youtube-dl for streaming videos from YouTube and saving them. Everything was going smoothly until I encountered an issue when trying to stream a video that exceeded on ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

What is the best method for passing a JavaScript object to PHP using Ajax?

I have looked into similar questions like this and this, but none of them have helped me solve my issue. When I check the console log for my data, it displays the following: Object["row_LM#00000010", "row_LM#00000002", "row_LM#00000009", "row_LM#00000008" ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

Converting PHP code to Typescript

Currently, I am working on developing a function for firebase that will trigger a POST request to call a specific URL. While I have successfully implemented GET requests, tackling the POST method has proven to be more challenging. I have some sample code ...

Sorting columns using custom conditions in DataTables

Within a PHP project I am working on, I have encountered a need to organize a specific column using a custom condition or order rather than relying on the default ordering provided by DataTable (ascending or descending). The project involves four distinct ...

What is the best way to connect DataTable() to an already existing HTML <table> by utilizing Vue.js and populating it with data from an array using a v-for loop

Having trouble implementing DataTable features like search field and column sorting in Vue.js for my table. I have included the original datatable.min.js in the <head> section, and also added and called another custom.js file with the following cont ...

Disabling the ripple effect on the primary action in React Material lists: A Step-by-Step

I was attempting to include two action buttons at the opposite ends of a list component. https://i.stack.imgur.com/juv8F.gif When clicking on the secondary action (delete icon on the right), the ripple effect is confined to just the icon. On the othe ...

Adjust the autofocus to activate once the select option has been chosen

Is there a way to automatically move the cursor after selecting an option from a form select? <select name="id" class="form-control"> <option>1</option> <option>2</option> <option>3</option&g ...

Breaking Long Strings into Multiple Lines Using React Material UI Typography

Currently, I am working with ReactJS and incorporating MaterialUI components library into my project. However, I have encountered a problem with the Typography component. When I input a long text, it overflows its container without breaking onto a new lin ...