Guide on integrating database information into an array with Vue.js

I'm having trouble retrieving data from Firestore and applying it as my array. I expect to see objects in the console but nothing is showing up. Should the method be called somewhere in the code? My method created() is functioning, but only when I handle the event by using @click - then my array is updated (added from the database) and also shows in the console. I have read the documentation from Firebase and the result is the same. I just started learning Vue.js a couple of days ago. Below is my code:

<template>
    <div class="index container">
        <div class="card" v-for="smoothie in smoothies" :key="smoothie.id">
            <div class="card-content">
                <i class="material-icons delete" @click="deleteSmoothie(smoothie.id)">delete</i>
                <h2 class="indigo-text">{{smoothie.title}}</h2>
                <ul class="ingredients">
                    <li v-for="(ing, index) in smoothie.ingredients" :key="index">
                        <span class="chip">{{ing}}</span>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
    import db from '@/firebase/init.js'

    export default {
        name: 'Index',
        data() {
            return {
                smoothies: [
                    // {title: 'Banana shake', slug: 'banana-shake', ingredients: ['banans', 'granats'], id: 1},
                    // {title: 'Morning brew', slug: 'morning-brew', ingredients: ['banans', 'orange'], id: 2},
                ]
            }
        },
        methods: {
            deleteSmoothie(id) {
                this.smoothies = this.smoothies.filter(smoothie => {
                    return smoothie.id != id
                })
            },
            created() {
                db.collection('smoothies').get()
                    .then(snapshot => {
                        snapshot.forEach(doc => {
                            console.log(doc.data())
                            let smoothie = doc.data()
                            smoothie.id = doc.id
                            this.smoothies.push(smoothie)

                        })
                    })
            }
        }
    }
</script>

firebase

import * as firebase from "firebase/app";

import "firebase/analytics";

import "firebase/auth";
import "firebase/firestore";


const firebaseConfig = {
    ...
};

const firebaseApp = firebase.initializeApp(firebaseConfig)

export default firebaseApp.firestore()

Answer №1

The placement of created() needs adjustment. It is important to place lifecycle hooks in the root options object. Remember, methods are just functions stored as properties.

    export default {
        name: 'HomePage',
        data() {
            return {
                smoothies: [
                    // {title: 'Strawberry Delight', slug: 'strawberry-delight', ingredients: ['strawberries', 'cream'], id: 1},
                    // {title: 'Tropical Paradise', slug: 'tropical-paradise', ingredients: ['pineapple', 'coconut'], id: 2},
                ]
            }
        },
        created() {
                db.collection('smoothies').get()
                    .then(snapshot => {
                        snapshot.forEach(doc => {
                            console.log(doc.data())
                            let smoothie = doc.data()
                            smoothie.id = doc.id
                            this.smoothies.push(smoothie)

                        })
                    })
        },
        methods: {
            removeSmoothie(id) {
                this.smoothies = this.smoothies.filter(smoothie => {
                    return smoothie.id != id
                })
            }
        }
    }

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

Tips on reloading or refreshing a react-table component using my form component

I currently have two reactJS components set up: CustomerForm component, which includes a form along with form handling code. CustomerList component, which utilizes react-table to list the customers. Both components are fully functional and operational. ...

Is it possible to implement an authentication guard in Angular and Firebase to verify if the user is currently on the login page?

My Current Tools Using Angular and Firebase My Objective To implement an Auth Guard that can redirect users based on specific conditions Current Progress I have set up an auth guard on various components which redirects users back to the login page ...

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Why do we even need Angular controllers when directives can perform the same tasks as controllers?

As a new Angular developer, I have to say that I am really impressed with the architecture of this framework. However, one thing that puzzles me is the existence of controllers. Let me elaborate: Services in Angular seem to have a clear purpose: 1) Store ...

Tips for creating a gradual fade-out effect on a bootstrap modal window

One issue I'm facing is with my modal dialog (#busyIndicator). It simply displays a message that reads "Please Wait". Sometimes, the operation it's tied to completes so quickly that the visual transition between showing and hiding the dialog beco ...

Inserting data into a JavaScript database

When attempting to add a new row to a datatable and submit it to a JSP for database insertion, an error is encountered. The error message reads: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the r ...

Best way to eliminate duplicate requests in your Vue js application

Currently, I am using axios version <0.22 and I am trying to implement cancelToken but I am facing some difficulties. I have implemented the code as shown below, however, it is not working as expected. Can someone please guide me on how to properly use ...

AngularJS - Controller routing to open link in new tab based on condition

Within my application, there are two distinct types of profiles available for organisations. When a user interacts with a profile name, the system must first determine if a premium profile exists for that organisation. If a premium profile is found, the us ...

I need to know how to send a "put" request using JavaScript and Ajax

My task involves programmatically updating a spreadsheet using my code. I am able to write to a specific cell within the spreadsheet with the following function: function update(){ jQuery.ajax({ type: 'PUT', ...

Create a correct v-model value by utilizing a dot notation string as a reference to the data object

Recently, I created a proxy-component that dynamically renders different components based on the specified :type. Everything was functioning smoothly until I encountered an issue with nested objects within the formData object. An example of this problem i ...

Directives causing disruption to one another

Two directives are at the same level in my code: function signUpForm(djangoAuth, Validate){ return{ restrict:'A', controller:["$rootScope","$scope",function($rootScope, $scope){ $scope.submitFunction = function(formData){ ...

My mongoose sort function doesn't seem to be functioning properly. What could be the issue?

Hey there! I've got a simple API up and running on Node.js, using MongoDB as my database with Mongoose for querying. The issue I'm facing is related to sorting data using the mongoose 'sort' method. Instead of behaving as expected, it s ...

Tips for sending information to a modal window

I need to transfer the userName from a selected user in a list of userNames that a logged-in user clicks on to a twitter bootstrap modal. I am working with grails and angularjs, where data is populated using angularjs. Set-Up The view page in my grails a ...

Tips for creating a two-tier selection filter system

I'm having an issue with this code. My objective is to create two filters for this table. The select element with id="myInput" should determine which rows appear in the table and apply the first filter. Here is the JavaScript code: function myFunctio ...

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

Troubleshooting HTTP Response Body Encoding Problem in Node.js

When making HTTP requests with the native 'http' module, unicode characters are not displayed correctly in the response body. Instead of showing the actual value, question mark characters appear. Below is a snippet of the code that I am working w ...

Leverage the power of Shopify API to retrieve a list of all products by making a request through

My website is custom built on node.js, and I am looking to retrieve all of my products in a single GET request. Unfortunately, the Shopify buy-button feature does not allow me to display all products at once due to pagination, hindering my ability to effec ...

Ways to showcase a variable's value in conjunction with text using .html() method

Hello, I need assistance with printing a value in a popup window. Below is the code I am using: "code" $('#warning').html('<p style="font-size: 12px;padding-top: 13px;">The updated list value is <p>' + var11); https://i.s ...

Guide on creating my inaugural HTML embeddable widget?

A client recently requested me to create a JavaScript (MooTools)/HTML/CSS/PHP based game as a deployable widget. This will be my first time developing a widget, so I am seeking advice and insights to help me navigate any potential challenges from experie ...