Saving an incremented number using Vue JS in Firebase database

I have a VueJS app integrated with Firebase JSON database where I'm trying to implement a feature that allows users to update the vote count of a comment by clicking an arrow (similar to upvotes on this website). The function works properly, but the Vue Model fails to update Firebase, resulting in the loss of the updated vote count upon refreshing. You can find my code on CodePen: http://codepen.io/Auzy/pen/evowdd/ (Please note that I use Pug and Stylus for styling; click the arrow in the top right corner to view normal HTML/CSS).

JavaScript:

// Initialize Firebase
var config = {
    databaseURL: "..."
};
const firebaseapp = firebase.initializeApp(config);
const db = firebaseapp.database();
const commentsRef = db.ref('test');

const app = new Vue({
    el: '#app',
    data: {
        comments: [],
        newComment: {
            name: '',
            comment: '',
            votes: 0
        },
    },
    methods: {
        addComment() {
            commentsRef.push(this.newComment);
            this.newComment.name = '';
            this.newComment.message = '';
            this.newComment.votes = 0;
        },
        vote: function (voteType, comment) {
            if (voteType === "up") {
                comment.votes++
            } else if (voteType === "down") {
                if (comment.votes <= -10) {
                    return;
                }

                comment.votes--;
            }
        },
    },
    firebase: {
        comments: commentsRef
    },

})

Answer №1

After some research, I have finally cracked the code. If you have a superior solution, please share.

Check out the revised approach along with additional explanations:

voteIncrement(comment) {
    comment.votes++ //incrementing the vote count
    const key = comment['.key']; //retrieving key of modified comment
    delete comment['.key']; //since Firebase has trouble handling keys, VueFire is the workaround.
    this.$firebaseRefs.comments.child(key).set(comment) //updating the Firebase record that matches the key
},

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

Inquiry from a newcomer: ASP.NET with jQuery

I am working on a webform with a file upload button that has some specific requirements. Whenever the file is uploaded using the button, I need the C# code behind to execute first before any jquery functions are called. <script> $(document.read ...

Improving functions in vue.js

Currently working on my personal project, which is an HTML website containing tables generated through vue.js. I believe that my code could be simplified by refactoring it, but I am unsure about where and what changes to make. Below is the section of the c ...

Is there a way to track and detect alterations to an element using JavaScript or jQuery

Can I detect the addition of a specific CSS class to an element without having to create a new event? ...

Obtain the value of v-model in a child component within VueJS

In my Vuetify App, I have implemented a Vue2Editor using a custom component called text-editor. Here is how it looks: <vue-editor :value="text" @input="updateText" ></vue-editor> The props for this component are defined as follows: props ...

The main.js file will be served by nodeJS using express

After developing a nodeJS server using express, I encountered an issue where the server was only delivering the index.html file and not the accompanying main.js file. Both files are located in the same directory. app.get('/', function (req, res) ...

Error: Python is not detected in the command line or npm configuration

I've been stuck on this issue for a while now, despite checking multiple posts for a solution. My problem revolves around deploying Firebase functions. So far, I have executed npm install -g firebase-tools, npm firebase login, and firebase init funct ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

The concept of recursively exporting modules in Node.js modules

Looking for a way to recursively export all .hbs files in a NodeJS 14+ project main JS. I attempted the following: module.exports = () => ({ partial : __dirname + "/../partial/**.hbs", helper : __dirname + "/../helper/*.js" } ...

What is the process for inserting or removing a row with Javascript?

Currently, I am in the process of working on some HTML/PHP code which is displayed below. <h3 style="text-align:center;margin-top:45px;">Sitting Days</h3> <div class="sitting-days" style="display:flex; justify-content:center; margin-bottom ...

Scaling Images using HTML and CSS

Hey there, I'm currently learning web development and running into a bit of trouble with creating responsive images. Can anyone give me some guidance on what changes I should make in the code below? Here's the HTML code: <div class="caro ...

What could be the reason for document.body.style.backgroundColor not working properly?

I am currently experimenting with a logic that triggers the screen to turn black upon pressing the print screen key. Despite changing the background color, it is not functioning as expected. The console has detected a change in value. What could be going ...

Enhance Your Search Functionality with an Angular Pipe

I created a custom pipe that filters the search field and displays a list of items based on the search text. Currently, it only filters by companyDisplay, but I want to also filter by companyCode and companyName. JSON [{ companyDisplay: "ABC", co ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

When selecting the top edge in React flow, it will automatically select the bottom

Documentation: Example from documentation: Steps to replicate issue: Drag and drop any node to a different location Select the top edge handle of the moved node Try dragging the edge out and notice that the bottom edge gets selected instead of the top e ...

Can React Slick be configured to display a Carousel within another Carousel?

Can React Slick support a Carousel within another Carousel? import Slider from "react-slick"; <Slider {...settings} > <div/> <div> <Slider {...settings} > ...

Keeping Vuex state in harmony with Firebase

When it comes to keeping my Vue.js state in sync with Firebase, I have implemented a strategy that involves setting up references to Firebase, getters, mutations, and actions in a separate folder within the store. So far, everything seems to be working fin ...

"Enable real-time editing with inline save/submit feature in

I'm struggling to figure out how to extract the modified content from a CKEditor instance and send it to a URL. I've been referencing something like this: but I can't seem to determine how to save the changes. Is there a way to post the up ...

The script fails to work correctly when displaying the data

Last night, I finally cracked the code on how to transfer data from my form on the index page to the content page, and then display the results inside the content div back on the index page. However, a new challenge has emerged. My Javascript function (re ...

MUI: The value you have chosen for the select component is outside the acceptable range - `[object Object]`

I'm currently in the process of developing a custom Select component that offers both single and multi-selection features. Below is how I initialize the components: const vendorList = [ { label: "John", value: "668", } ...

Removing API request in React.js

My approach: deleteSample = () => { this.sampleService .deleteCall(this.props.id) .then((response) => { window.location.reload(false); }) .catch((error) => { console.log ...