Even when using a conditional statement in JavaScript, Firebase continues to make multiple calls

I am in the process of creating an application using Vue.js and Firebase. Despite being new to Firebase, I have encountered some issues that I am struggling with. Specifically, I am trying to store names and email addresses in the database. My goal is to first check if the email address provided already exists in the database. If it does not, I want to execute another function to store the name and email address. However, if the email address is already present in the database, I would like to display an alert message and prevent the submission.

So far, I have been able to successfully check for the email in the database and trigger the alert message. I can also retrieve data from the database without any problems. The issue arises when I enter a new email address that is not yet stored in the database. Upon entering a new email address (along with a name), the system checks the database and initially returns false. However, it then inexplicably makes another call, which results in a true response indicating that the email is already on file. As a result, the alert about the email's presence is displayed simultaneously with the initial false response. Subsequently, the system proceeds to run another function to store the data because of the false response received during the initial call.

Here is the JavaScript code I am currently using:

checkForm() {

        let app = this;

        if (this.name == '' || this.emailaddress == '') {
            alert('Please fill out the form completely');
        } else {
            app.getFirebase();
        }

},

getFirebase() {

        let app = this;

        var ref = firebase.database().ref().child('/aanmeldingen/');
        ref.on('value', function(snapshot) {

            const array = [];

            snapshot.forEach(function(childSnapshot) {
              var checkEmail = childSnapshot.val().email;
              array.push(checkEmail);
            });

            const res = array.includes(app.emailaddress);
            console.log(array);
            console.log(res);

              if(res) {
                alert('You have already entered the giveaway');
              } else {
                app.store();
              }
        });
},

store() {
                this.step_two = false;
                this.active_two = false;
                this.active_three = true;
                this.step_three = true;

                let app = this;

                firebase.database().ref('/aanmeldingen/').push({
                username: app.name,
                email: app.emailaddress,
                });
}

Below is a screenshot from the console log after entering the name "Jane," who is not found in the database:

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

Answer №1

It is recommended to utilize the once() method instead of on(). Using on() keeps the listener attached, causing it to trigger again when new data is added with store().

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

Two arrays with similar content connecting links to each other

Two sets of data are being received from an Ajax request. The first set consists of titles that I own, while the second set contains all existing titles along with their respective URLs. My goal is to link the titles in the first set to the URLs found in t ...

Securing the IDs of Stripe customers and Firebase users through encryption

Do you think it's necessary to encrypt the Stripe customer ID within a NextJS environment? I have an API route in NextJS that updates the customer's email address using the Stripe Customer ID from a Firestore database (using the Stripe extension ...

What is the best way to apply a class to a container when a component in AngularJS receives focus or is clicked?

I am trying to apply a class to the container when either the input field is focused or when the dropdown component receives focus or is clicked. The class should be removed when the focus is lost. The requirement is for the input container to have the &a ...

"Encountering a duplicate key error when reordering columns in PrimeVue's DataTable component

I have encountered an unusual issue with a datatable: <DataTable :scrollable="true" :value="shipments" :totalRecords="shipments.length" :reorderableColumns="true" :alwaysShowPaginator="fal ...

I've been encountering a recurring issue of receiving NaN followed by a number in React. Any suggestions on how to resolve

click here to see the image const number = parseInt(props.detail.price,10) const toLocale = number.toLocaleString("ko-KR") console.log(toLocale) return ( <div> <Descriptions title="Product ...

Expanding choice by incorporating additional or default selections with ng-options

I am currently working on a tag-manager feature within an angular form that utilizes two dropdown menus (in this example, a food category and a specific item). The functionality I am aiming for is when a user selects a food category, the item dropdown shou ...

Creating GraphQL fragments dynamically from an array

After reviewing other responses, it appears that the suggested method for constructing dynamic queries is to utilize fragments in the following manner: const series1Q = gql` fragment series1 on timeseriesDataQuery { series1: timeseriesData(sourceId: ...

Checking the status of a mongos connection in Node.js: A simple guide

Imagine a scenario where our Node.JS app is connected to the Mongos process, but suddenly Mongos crashes. How can our app be notified of this failure? var db = null; mongo.MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, mydb ...

Troubleshooting a problem with the interactive YouTube player in Safari

I have successfully implemented a custom YouTube player on my website, allowing users to watch videos within a modal box. Below is the code for reference: JS & HTML: <script src="https://www.youtube.com/iframe_api"></script> <script typ ...

Move content to the bottom of a div element while the user is scrolling

I have a website that functions smoothly with typical user scrolling. Nevertheless, I am interested in incorporating a feature where the user is automatically moved to either the bottom or center of the div element upon scrolling. The elements in questio ...

Troubleshooting Vue 3 password validation issue

Creating a registration form for a website using Vue 3. I have a method that checks the values of the password and confirm password fields and compares them. If they match, nothing happens. However, if they do not match, a red label appears, and the submit ...

Minicart.js - Products successfully added to cart but cart fails to appear on screen

Currently, I am facing an issue with my button click function that is supposed to add an item to the cart using the Minicart.js library from minicartjs.com. Although items are successfully being added to the cart upon clicking the button, the cart itself i ...

What is the best way to retrieve the values from the labels for two separate buttons?

I designed a pair of buttons with a single label below. Both buttons acted as standalone entities. <label for="buttons" class ="val">0</label> <input class="btn btn-primary button1" type="button" ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Adjusting camera orientation and field of view using trackball manipulation controls in THREEJS

Manually setting the position and fov of the perspective camera in THREE.JS is working as expected for me. However, when I try to interact with the scene later using the TrackBall Controls, it just shows a black screen with no errors. Check out this JS Fi ...

Dealing with success in a personalized JavaScript function

When making an ajax call, it is possible to add success handling, and I would like to incorporate similar logic into my custom functions. I currently have 6-10 custom functions that need to run either sequentially or independently. They are currently dais ...

Using Javascript to send a SOAP request to a WCF web service hosted on Azure

Currently facing an issue with my WCF web service hosted on Azure as a cloud service. I am encountering difficulty in sending a POST SOAP request from an HTML/JS web application due to restrictions on cross-domain communication. Despite trying different PO ...

The Vue Typescript callback is automatically assigned the type "any" when not explicitly defined

Encountering a TypeScript compiler error while using an anonymous function with lodash debounce in my Vue component's watch option. The error states: "this implicitly has type any." Below is the code snippet of my component: export default defineComp ...

Navigating tables with jQuery using a loop and extracting data from two tables with matching row names

I am facing a challenge with a function that combines data from two tables, each containing a column named "name". How can I specify which table's name should be displayed? function createTableRow(customers) { var data = JSON.parse(customers.resu ...

How can I generate a distinct reference for a nested v-for loop?

I have a structured array of objects that looks like this: itemList: [{ itemName: "Item One" },{ itemName: "Item Two", children: [{ itemName: "Child One" },{ itemName: "Child Two" }] },{ item ...