Initially, I followed the advice from @kissu () but encountered an issue where it resulted in multiple socketIO connections being created. This caused problems such as sending messages to everyone except the sender not functioning as expected due to receiving the message through other client connections.
My current approach involves creating an object of the class and importing the object instead of the class itself.
src/services/socketio.service.ts
import type { Socket } from "socket.io-client";
import { io } from "socket.io-client";
import type { ClientToServerEvents, ServerToClientEvents } from "../communication";
class SocketIOService {
socket: Socket<ServerToClientEvents, ClientToServerEvents>;
constructor() {
this.socket = io(process.env.VUE_APP_SOCKET_ENDPOINT || "http://localhost:3000" );
}
}
// create an instance/connection here
export const socket = new SocketIOService().socket;
src/components/myButton.vue
<script setup lang="ts">
// import the object instead of the class
import { socket } from "../services/socketio.service";
async function buttonPress() {
socket.emit("buttonPressed");
}
</script>
This modification ensures that multiple components will share the same socketio connection :)