The scenario involving TypeScript, MySQL, and Socket.IO where re-emitting occurs after a failed login attempt

I'm encountering an issue where, after failing to sign in and then successfully signing into my game, it creates a game instance for every failed login attempt. This same problem occurs with failed sign-up attempts as well.

I would like to provide more code for context, but Stack Overflow requires even more details which I am unsure of. Therefore, I'll just link my repository.

Single failed attempt: image

Two game instances created: image

My repository: elevaidusTS

SERVER

        socket.on('signIn', (signInInfo: any) => {
            let sql = 'SELECT * FROM player WHERE username = ? AND password = ?';
            var query = this.db.query(sql, [signInInfo.username,signInInfo.password], (err, res) => {
                if (err) {
                    console.log(err);
                    socket.emit('errorFromBackend', err.code);                        
                }else if(res.length === 0){
                    socket.emit('errorFromBackend', 'username and or password was incorrect');                 
                }else{
                    console.log(`\n\n===============>\t Player logging in\n`)
                    console.log(`===============>\t username: ${signInInfo.username}\n`)
                    console.log(`===============>\t password: ${signInInfo.password}\n`)
                    this.CreatePlayer(socket, { player: res[0], isNew: false });
                }
            })
        })

CLIENT

   public SignIn(): void {
    this.socket.emit('signIn', {username: signInUsername.value, password: signInPassword.value })
    this.socket.on('signedIn', (playerInfo: any) => {
      this.CreateGame(playerInfo);
    })
    this.socket.on('errorFromBackend', (err: string) => {
      alert(err);
    })
  }

  public SignUp(): void {
    this.socket.emit('signUp', {username: signInUsername.value, password: signInPassword.value })
    this.socket.on('signedUp', (playerInfo: any) => {
      this.CreateGame(playerInfo)
    })
    this.socket.on('errorFromBackend', (err: string) => {
      alert(err);
    })
  }

Answer №1

Instead of placing my listener within the same function as the emitter, I discovered that by pressing the signup/signin button, a new instance of my listener was being created. This meant that every time the listener was triggered, all instances of the listener would execute the task.

For more information on this topic, check out this insightful post: helpful post

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

Automating the linking of tsd definitions with bower and npm: A step-by-step guide

Currently, I am in the process of transitioning an existing project to TypeScript which includes numerous bower and npm dependencies (bower.json and package.json). As mentioned on the tsd github page, TSD facilitates the discovery and linking of defini ...

Enhancing responsiveness in the auto-suggest feature

I am struggling to update the added value in the DOM after pushing a new element into the array of options. Despite my efforts, the update is not reflecting in the DOM. import { Component, OnInit } from '@angular/core'; import { FormControl } fro ...

Experiencing garbled text when retrieving Hebrew language information from the database

Having trouble with displaying Hebrew text in a PHP project? When attempting to select Hebrew data from the phpMyAdmin database, it always appears as gibberish. Despite trying various solutions found on different websites, the issue remains unresolved. Be ...

What is the process for recording information using a static method in TypeScript within a class?

For my school project, I'm struggling to retrieve the names from a class using a method. One class creates monsters and another extends it. abstract class genMonster { constructor( public id: string, public name: string, public weaknesse ...

What is the method to incorporate the current time into a date object and obtain its ISO string representation?

I'm using a ngbDatePicker feature to select a date, which then returns an object structured like this: {year:2020, month:12, day:03} My goal is to convert this date into an ISOString format with the current time. For example, if the current time is 1 ...

Is it possible for me to use an array as an argument for the rest parameter?

One of the functions in my codebase accepts a rest parameter. function getByIds(...ids: string){ ... } I have tested calling getByIds('andrew') and getByIds('andrew','jackson'), which successfully converts the strings into a ...

Managing inventory quantities in MySQL using PHP when item names match

After receiving an item from a company, I enter all the item details in my PHP form and save it in MySQL There are two tables in MySQL - one is "receive" and the other is "stock" When receiving an item, it is saved in both the "receive" and "stock" table ...

The process of sharing a complete full-stack (ReactJS, NodeJS, socketIO) project on GitHub using Git Bash command line

Recently, I completed a project on realtime chat and now I am looking to upload it to my GitHub repository. My folder structure is as follows: enter image description here I am currently unsure how to upload the entire project to GitHub using git bash com ...

How to send multiple queries in one request with graphql-request while using getStaticProps?

I am currently utilizing graphCMS in combination with NextJS and have successfully implemented fetching data. However, I am facing an issue where I need to execute 2 queries on the homepage of my website - one for all posts and another for recent posts. q ...

`Filter an array retrieved from the backend in a TypeScript environment`

I have asked other questions in the past, but I received unhelpful answers. I am still looking for proper solutions. Currently, I am retrieving an array from the backend using Redux. const { movies, message } = useAppSelector(state => state.movies); ...

Filter Laravel Eloquent relationship based on the latest pivot record

I have a scenario with 3 tables: user, role, and the pivot table named user_role. The user and role tables have a many-to-many relationship. In addition, every assignment (role to user) in the user_role table includes a timestamp, allowing me to determine ...

Is there a way to extract the password from the SQL database while preventing the output from being quoted?

Here is my current code: import mysql.connector import hashlib cnx = mysql.connector.connect(user='root', password='!Joshua1', host='127.0.0.1', database='pa ...

Tips for resolving type inference for a component variable in a jest Mount test created using reactjs

I am currently working on a React project that is built in Typescript, specifically dealing with a unit test involving the use of mount from Enzyme. As I strive to align the project with the tsconfig parameter "noImplicitAny": true, I am faced with the cha ...

Tips for preventing duplication of the interface in Typescript React

Embarking on my first Typescript app, I am determined to maintain a structured approach by keeping styles and components in separate files. With an ambitious project scope of numerous components, I intend to utilize props for calling classes, ensuring each ...

Jasmine reported that there were no specifications found in the Angular project written in TypeScript

I'm facing a frustrating issue with Karma and Jasmine in my Angular 9 project. Despite setting up the configuration files correctly, I keep getting a "No specs found" message when running ng test. I have tried various adjustments, including creating d ...

Updating dynamically added rows in MySQL using PHP

One challenge I am facing is with a form that has the ability to dynamically add rows by clicking on an 'add new row' button. Each added row consists of 2 fields: Description and Completed Date This is the SQL table structure used to store thes ...

Executing HTTP POST requests in Zend/PHP to interact with controller and mapper PHP classes

For our Android app to save data in MySQL, we need to make a POST request to a server running PHP Zend. Our supervisor has instructed us to create a class that follows the Zend MVC structure, specifically: GcmUsersController.php class GcmUsersController ...

Save mathematical equations written in HTML text boxes to a MySQL database

How can I display mathematical formulas in a text input and store them in a database? I need to be able to display formulas like the ones shown in the image at this link: Currently, when I copy any formula into the text box, it gets converted to normal t ...

Dealing with request-specific or session-specific data in LoopBack 4

I am currently facing a challenge within our LoopBack4 application. We have implemented controllers and are using JWT for Authorization. In the token's payload, we include a list of rights granted to the requesting user. Additionally, we have added an ...

The 'data-intro' property cannot be bound to the button element as it is not recognized as a valid property

I've been using the intro.js library in Angular 8 and so far everything has been working smoothly. However, I've hit a roadblock on this particular step. I'm struggling to bind a value in the data-intro attribute of this button tag. The text ...