Creating a basic voting system with Vue.js and Firebase: A step-by-step guide

Hello, and please forgive me if this question seems too basic, but I'm just starting out and feeling a bit overwhelmed.

I'm attempting to allow a user to vote on and then remove their vote from an item posted by another user using the same button. Essentially, I'm trying to create a functionality similar to the favorite feature on Twitter. I've been able to implement the voting part, but I'm struggling with removing the vote.

Here is the code snippet for the upvote (which is working for me):

import { mapState } from 'vuex'
const fb = require('../firebaseConfig.js')

export default {
    computed: {
        ...mapState(['userProfile', 'currentUser', 'items'])
    },
    methods: {
        upvoteItem(itemId, itemUpvotes) {
            let docId = `${this.currentUser.uid}_${itemId}`
            fb.upvotesCollection.doc(docId).get().then(doc => {
                if (doc.exists) { return }
                fb.upvotesCollection.doc(docId).set({
                    itemId: itemId,
                    userId: this.currentUser.uid
                }).then(() => {
                    // update item upvotes
                    fb.itemsCollection.doc(itemId).update({
                        upvotes: itemUpvotes + 1,
                    })
                })
            }).catch(err => {
                console.log(err)
            })
        },
    }
}

And here is the HTML for triggering the upvote (and displaying the counter):

<button @click="upvoteItem(item.id, item.upvotes)">{{ item.upvotes }}</button>

Any suggestions on how to proceed?

Answer №1

Despite following the recommended method, I have not been successful in executing it properly.

Nevertheless, I have been exploring alternative approaches to tackle the issue.

One particular method caught my attention (even though it might not seem logical, for reasons unbeknownst to me).

1) Initially included "upvoted: false" when the item was created

2) Implemented two functions (one for upvoting, and another for downvoting)

methods: {
            upvoteItem(itemId, upvotes) {
                let docId = `${this.currentUser.uid}_${itemId}`
                fb.upvotesCollection.doc(docId).get().then(doc => {
                    if (doc.exists) { return }
                    fb.upvotesCollection.doc(docId).set({
                        itemId: itemId,
                        userId: this.currentUser.uid
                    }).then(() => {
                        fb.itemsCollection.doc(itemId).update({
                            upvotes: upvotes + 1,
                            upvoted: false
                        })
                    })
                }).catch(err => {
                    console.log(err)
                })
            },
            downvoteItem(itemId, upvotes) {
                let docId = `${this.currentUser.uid}_${itemId}`
                fb.upvotesCollection.doc(docId).get().then(doc => {
                    if (doc.exists) { return }
                    fb.upvotesCollection.doc(docId).set({
                        itemId: itemId,
                        userId: this.currentUser.uid
                    }).then(() => {
                        fb.itemCollection.doc(itemId).update({
                            upvotes: upvotes - 1,
                            upvoted: true
                        })
                    })
                }).catch(err => {
                    console.log(err)
                })
            },

3) Utilized a ternary operator for on-click events

<button @click="item.upvoted ? downvoteItem(item.id, item.upvotes) : upvoteItem(item.id, item.upvotes)">{{ item.upvotes }}</button>

However, the ternary operator seems to work only on the initial click, and I am unable to get it to function on subsequent clicks!

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

How do you manage dependencies for nested components within Angular2?

Encountering an Issue: browser_adapter.js:76 Error: Cannot resolve all parameters for NestedComponent(undefined). Make sure they all have valid type or annotations. at NoAnnotationError.BaseException [as constructor] Diving Deeper Into the Problem: ...

Exploring the world of Vue.js with the latest vue-cli 3.0 and integrating Google Web

I'm completely confused about incorporating Google Fonts into my project. Despite installing the google-fonts-webpack-plugin and attempting to configure it correctly, the html is not being injected. Perhaps I am approaching this problem from the wron ...

Can data be transferred between components and displayed in Vue Js?

Article Header <article> <CardBody @submit-form="handleFormSubmit" /> </article> Main Article Script export default { methods: { handleFormSubmit(event, data) { console.log('Form submitted with ...

Retrieve the attribute from the element that is in the active state

I'm facing a challenge in determining the active status of an element attribute. I attempted the following approach, but it incorrectly returned false even though the element had the attribute in an active state - (.c-banner.active is present) During ...

Executing a function every time a prop is updated within the component

I have a prop named transcript in one of my components. Whenever I speak a voice intent, it gets updated. I want to execute a function every time the transcript changes and pass the transcript as an argument. In this code snippet, I attempted to use an On ...

What could be the reason behind the malfunctioning of a custom filter in this specific Vue 3 application?

In my development project, I am creating a Vue 3 CRUD application for managing Users. The goal is to display the users in reverse order so that the newest additions appear at the top. To achieve this, I have implemented a custom filter as shown below: reve ...

When trying to click on an HTMLTableRowElement, an Uncaught ReferenceError occurs in React.js and jQuery, stating that the function is

When I was working on my web app, I encountered an issue while trying to create a table. Upon clicking on it, I received an error message: Uncaught ReferenceError: (function) is not defined at HTMLTableRowElement.onclick Here is the code for the table: $( ...

Transferring data from PHP to AJAX and then injecting it into an SQL query

I've been attempting to pass a datepicker variable into an onclick ajax function, which then sends it to another ajax method that passes the variable to an SQL query. The result of the query is then passed back into the ajax function to generate a cha ...

The CSS toggle feature in the React component is not being implemented as expected

I am currently working on a component that maps over an array and displays a series of buttons that render specific content: export const Bookings = ({bookings}) => { const [selectedBooking, setSelectedBooking] = useState(false); const handleSel ...

toggle the outer div along with its corresponding inner div simultaneously

On one of my pages (let's call it "page1"), I have multiple divs, some nested within others. These divs are initially hidden and toggle on when a specific link is clicked (and off when clicked again). To view a nested div, the outer div must be opened ...

The received reply does not align with the set parameter configuration:

Encountering an issue with Angular $resource: error description Error: error:badcfg Response does not match configured parameter: Error in resource configuration for action `array`. Expected response to contain an object but got an {2} Initialization of ...

Utilize Node.js to efficiently send emails to a group of subscribed clients

I have a Node.js website on my local system that sends email notifications to users about trending articles or posts. Here's how my code works: app.get('/:articlename', (req, res)=>{ conn.query(`SELECT views,isAlreadySent FROM article_ta ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

Utilize Mongoose to seamlessly integrate online shopping cart items into MongoDB

I am facing an issue while trying to insert a shopping cart of items in the form of a JSON object into a MongoDB collection using a mongoose schema. Although the customer's ID is successfully stored (extracted from the User DB), unfortunately, the ca ...

Error encountered while trying to retrieve Instagram JSON data via request due to an abrupt end of input

I am attempting to retrieve the JSON data from Instagram's URL: . When I enter this URL in my browser, it displays the JSON information. However, I want to be able to access this data using Express so that I can extract any necessary information. co ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

Troubleshooting an expressjs server in parallel with electron

I have managed to successfully run an ExpressJS server alongside Electron by following the instructions provided in this post: Run Node.js server file automatically after launching Electron App However, I am facing an issue where there is no output from t ...

Exploring Vue 3 and Pinia: Achieving Reactivity in Stored Values

Currently, I am working on a project using Vue 3 with the Composition API and Pinia. Within my application, I have an auth store that retrieves the default email and password values from the store. import { useAuthStore } from "stores/auth"; const authSto ...

How to effectively utilize $emit in Angular?

Whenever I use {{callData}} in my HTML, the result of $scope.callData doesn't seem to be functioning properly. Is there something wrong with my code? I would greatly appreciate any help in resolving this issue. phonecatControllers.controller(&apos ...

Create a function that multiplies every element in an array by 2

This example involves some JavaScript code. Currently, I have written the following: var double = function (array) { var newArray = []; for(var i = 0; i<array.length; i++) { newArray.push(array[i]); newArray.push(array[i]); ...