Receiving unique socket IDs for two different socket.on events

Currently, I am in the process of developing a socket-based application using React and Node/Express. As part of this project, there is an event listener set up for when a user connects with io.on('connection'). Upon connection, the user is added to an array within the application using the

addUser({id:socket.id, name, room})
function, which is triggered during the socket.on('join') event. When attempting to send a message, I have implemented a handler for socket.on('sendMsg'), but it seems that a different ID is being passed to the getUser(socket.id) function.

io.on('connection',(socket)=>{
    socket.on('join',({name,room})=>{
        const user = addUser({id:socket.id, name, room})
        socket.join(user.room)
        socket.emit('message',{user:'admin',text:`${user.name}, welcome to the room ${user.room}`})
        socket.broadcast.to(user.room).emit('message',{user:'admin', text:`${user.name} has joined`})     
        socket.on('disconnect',()=>{
            console.log('usre left')
        })
    })
    socket.on('sendMsg',(msg, callback)=>{
        console.log('what the heck is this:', socket.id)
        const user = getUser(socket.id)
        console.log(user)

        io.to(user.room).emit('message', {user: user.name, text: msg})
        callback()
    })
})

const addUser = ({id, name, room}) =>{
    const existingUsers = users.find(user=>user.room === room && user.name === name)
    if(existingUsers) {
        console.log('not adding')
        return {error:'User name is taken'}
    }
    const user = { id, name, room}
    users.push(user)
    console.log('users updated, ' ,users)
    return user
}

const getUser = (userId) =>{
    console.log(users)
    return users.find(user=> user.id === userId)
}

I am at a loss as to why this unexpected behavior is occurring. Does anyone have any insights on this issue?

Answer №1

Issue resolved. The socket instance on the client side was being re-initialized each time.

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

Finding users with particular roles (discord.js version 12)

I am looking to display a list of users with a specific role. The goal is to show both the total number of users with that role and their usernames. Error: TypeError: Cannot read property 'members' of null module.exports = { name: "user ...

What is the best method for sending XML data to a URL using JavaScript within an Adobe AIR application?

I am currently developing an application that involves downloading an XML string from a URL and then posting it to another URL. I have managed to successfully download the XML string and can manipulate it using alerts, however, I am struggling with posting ...

Discovering time overlaps with Javascript and moment.js

In my calendar project, I am storing events for a day in an array. The start and end times are stored as String values in the following format: Example of events in a day const events = [{ "_id": "5bdf91a78197f0ced6c03496", "user": "5bd62237d6 ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Retrieve information following an Ajax call inside a pre-designed template

Upon rendering a page with data put together by EJS, the goal is to refresh a section (thirdRow) of the page whenever the user submits new data. The refreshed section should display both the newly submitted data and the existing data. Although I have obtai ...

Adding URIs to a post request using JavaScript

I'm struggling to understand how to include URIs in a POST request, similar to this API request: link to example This is my current request, but it's not functioning properly fetch(endPoint, { method: "POST", headers: { Authorization ...

Retrieve a file from a NodeJS Server via Express

I have encountered a similar issue that has been previously addressed in the following answered question: Download a file from NodeJS Server using Express However, I am still facing challenges with the filename displayed in the browser download dialog. ...

Is there a way to verify if a task has been completed and ensure that it is not repeated if already done?

Is it possible to use the "on" method to create a new .content and attach it to .mainPage only once when the mouse is over the existing .content? Check out this sample: http://jsfiddle.net/4Qs97/ <div class="mainPage"> <div class="content"&g ...

Discover the ultimate guide on developing a personalized file management system using the powerful node.js platform!

I have undertaken a rather ambitious project for myself. There exists a comprehensive tutorial on the website that outlines the process of establishing an online environment (resembling a user panel) where registered users can effortlessly upload various ...

Next.js production build encountering an infinite loading error

I have been utilizing the Next.js TypeScript starter from https://github.com/jpedroschmitz/typescript-nextjs-starter for my current project. The issue I am facing is that when I attempt to build the project after creating numerous components and files, it ...

"Error: Command 'npm' is not recognized as a valid internal or external command" encountered while using create-react-app

Why won't npm work for me? I've been trying to dive into the world of React and kickstart my learning journey. With Node installed, along with the create-react-app package, I thought I was all set. When I run commands like npm -v or create-reac ...

Clicking on ng-click can lead to the dissociation of the Angular factory

My situation involves a factory with a series of prototypes that need to call each other. The issue arises when the reference to "this" is mistakenly applied to the html template instead of the original factory class when using ng-click. For example: ang ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...

Is it possible to initiate a series of node tasks in a predetermined sequence?

I have developed a framework that currently requires 4 user inputs to install, which is quite cumbersome. I am looking for a way to streamline the process to just one input. Essentially, I am seeking a solution to execute those 4 commands with only one in ...

Adjust speed on various HTML5 video players

I'm looking to slow down all the HTML5 video players on my page to 0.5x speed. Currently, I have a JavaScript snippet that only affects one video player at a time. <script type="text/javascript"> /* play video twice as fast */ document.quer ...

Having trouble displaying a local image in CSS using EJS

Hey there, I'm currently working with EJS. In my CSS file, I've added a background image but it's not showing up when the page loads. Strangely, if I use a hosted image, it works perfectly. Here is my directory structure: https://i.sstatic ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

Manipulate md-select options with Angular using setValue

My goal is to update a select option, but I'm having trouble getting it to work properly. When I use this.eventForm.controls.venue.setValue(event.venue.name);, the value of venue changes to match event.venue.name. However, the select option itself doe ...

Manipulate and transform elements within an array using both Filter and Map functionalities in React

Below is the component I am working with: function Params(props) { const { Parameters } = useFetchParams(); return ( <div className='Params'> { Parameters && Parameters.map(parameter =&g ...

What is preventing me from iterating through a dictionary or an array of keys?

After trying to log the dictionary using console.log(JSON.stringify(this.idTitleDict)) as suggested by @Kobe, I noticed that it was showing empty curly braces. All the code related to this dictionary (including its declaration and population) can be found ...