• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

145
Views
socket.io getting error message while using broadcast

actually am trying to create chat app using vueJS and socket.io so here is what i have done so far

<script>
    import {io} from "socket.io-client";
    export default {
        data() {
            return {
                socketInstance: io("http://localhost:3001"),
            };
        },
        methods: {
          async handleSendMessage(message) {
            const postParams = {
                ip: this.userData.ip,
                message: message,
                user_type: "customer",
            };
            const {data} = await axios.post(
                "http://localhost:3001/api/message",
                postParams
            );
            this.messages.push(data.message);
            this.socketInstance.broadcast.emit("new_message", {
                message: data.message,
                socket_id: this.socketInstance.id,
            });
             //HERE AM GETTING ERROR WHILE USING BROADCAST
        }
},
        
        mounted() {
            this.socketInstance.on("new_message", ({message, socket_id}) => {
                if (message.ip == this.userData.ip) {
                    this.messages.push(message);
                }
            });
        },
    };
</script>

Basically handleSendMessage function is responsible for sending message and emit an event but when I do

this.socketInstance.emit("new_message", {
  message: data.message,
  socket_id: this.socketInstance.id,
 });

then it's works fine but as you know i will get duplicate messages so i used

this.socketInstance.broadcast.emit("new_message", {
  message: data.message,
  socket_id: this.socketInstance.id,
 });

and got following error

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'emit')

I don't know why am getting this error. Sorry for my bad English.

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

It is written in the socket.io documentation as follows:

Please note that broadcasting is a server-only feature.

.broadcast is only used on the server-side. You broadcast something to all connected clients, not client-to-client.

Related documentation

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error