Reputation: 301
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.
Upvotes: 0
Views: 298
Reputation: 561
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
Upvotes: 1