How to prevent socket.io executing an event for all users?

whenever I press a button on the client-side to send a emit a request to the server, that button executes for all connected users. I’d like to make it so that it only emits to the current user. is there any way I can do this?

client.js

handleForm = () => {
        socket.emit("request-uid");
        socket.on("uid", (uid) => {
            socket.emit("validate-data", {
                title: this.state.title,
                price: this.state.price,
                email: this.state.email,
                description: this.state.description,
                contact: this.state.contact,
                tags: this.state.tags,
            });
        });
    };
socket.on("refresh", () =>{
    alert("test!");
});

server.js

io.on("connection", function (socket) {
    console.log("user connected!");
    socket.on("request-uid", () => {
        io.emit("uid", crypto.randomBytes(4).toString("hex"));
    });

    socket.on("validate-data", (data) => {
            io.to(socket.id).emit("refresh");
        
    });
});

when I click the button that executes the handleForm() function it emits the sockets to every user that is currently on the site, regardless of whether or not they pressed the button.

even when I use io.to(socket.id) on the server side it sends it to everyone as well, I’m guessing this is because “validate-data” is running, and it sends a unique socket to emit to all users.

I just want it to send a request to the user that pressed the button.

Answer

io.emit('uid') sends the uid event to all client sockets, and then in the callback each client emits its own validate-data to the server. Change io.emit('uid') to socket.emit('uid') and you can also simplify io.to(socket.id).emit('refresh') to socket.emit('refresh').