Tips for implementing vue.js composition api with vue-3-socket.io

Is there a way to access the socket instance within the setup function of a Vue.js component?

I am utilizing vue-3-socket.io

in my main.js


import VueSocketIO from 'vue-3-socket.io'
import SocketIO from 'socket.io-client'

Vue.use(new VueSocketIO({
    debug: true,
    connection: SocketIO('http://metinseylan.com:1992', {}), 
    vuex: {
      store,
      actionPrefix: "SOCKET_",
      mutationPrefix: "SOCKET_"
    }
  })
);

Answer №1

My approach involves utilizing socket.io directly, without relying on a Vue Plugin:

export const useSocketIO = () => {
    const socket = io('http://metinseylan.com:1992')
    return {
        socket,
    }
}

Component

<script setup>
import { defineComponent } from 'vue'

const { socket } = useSocketIO()
socket.on('welcome', () => { console.log('welcome') })
  
</script>

Answer №2

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 :)

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

How can I implement Jquery ajax calls in various JavaScript functions?

I'm encountering an issue with a particular function in my code function readComm(){ $.post("something.php", {read:"read"}, function(data){ retVal = $.trim(data).toString(); console.log(retVal); return retVal; }); } T ...

Looking for a script that automatically swaps out a div at set intervals? You'll need to tweak it so that it only

I created a js script that dynamically changes the content of certain div elements at specified intervals. While I appreciate how it functions, I now need to modify it so that the script only executes once. Can someone help me achieve this? <script typ ...

Determine the frequency values and coordinates of the normal distribution curve (X and Y axes)

I have successfully implemented the Histogram chart using react-plotlyjs. The graph is working fine but now I need to draw the normal distribution curve using X and Y axes. While I have the coordinates for the X axis, the Y axis values are automatically ca ...

Utilizing Ternary Operators with User Input

In my latest project, I am developing a cutting-edge app that converts text to sound, utilizing input text from react-native-elements along with ternary operators. My main challenge now is figuring out how to validate whether the text input box is empty ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

The rc-form package in npm is issuing a Warning for the getFieldDecorator method when `defaultValue` is not being used as an option

Currently, I am on the rc-form 2.4.8 version and I am utilizing the getFieldDecorator method in my codebase. However, an issue has arisen: Warning: defaultValue is not a valid property for getFieldDecorator; the correct use is to set value, so please uti ...

Why is applying CSS on an li element using .css() in JQuery not functioning?

Hey there! Could you please review my code? I'm attempting to add a top position to the <li> element using a variable in jQuery, but I'm not sure how to do it. Here's the code: <script> $(document).ready(function(){ ...

Using React hooks to reset state in a reducer: step-by-step guide

event.js import React, { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link, useHistory } from 'react-router-dom'; import { addEvent } from '../actions/event'; ...

Creating a function to update data in a Node.js/MongoDB environment

Hey there! I'm new to working with nodejs and mongodb, and I'm trying to create a function that updates the win, lose, and draw record in my UserSchema. Here's my Schema: UserSchema = new mongoose.Schema({ username:'string', ...

Encountered an issue while trying to read properties of undefined (specifically 'meta') within a Vue 3 single-spa application

I've been working on a micro-frontend project, utilizing vue 3 and single-spa 5.9.3. Recently, I attempted to update one of the npm packages for a Micro-frontend to the latest release. The build process went smoothly, but it resulted in the following ...

Steps for regularly executing 'npm run build' on the server

My website doesn't require frequent content updates, as users don't always need the latest information. As a result, most pages are generated server-side and served as static pages. There will be occasional database updates that need to be visib ...

How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully. Successfully receiving response, converting blob to object ...

What is the best approach to display data in React fetched from an API request? If this is not the right method, what changes should be made to the JSX rendering to convert

As I begin my journey with React, I find myself questioning the best practices for displaying data. Should I always break down components into smaller ones rather than having one large component render everything? It seems like a good practice, but I' ...

The checkbox is not updating as anticipated

I'm currently developing a basic widget that allows the user to change the value of either the check box OR the entire div by selecting them. Below is the code I have implemented: $(document).ready(function() { $(document).on("click", ".inputChec ...

Issue with JavaScript causing circles to form around a parent div

I am struggling to position a set of circles around a parent div in my code. I want 6 circles to form a circle around the parent div, but they are not lining up correctly. Can someone help me identify what I'm doing wrong? var div = 360 / 6; var ra ...

The initialization process of Vue.js router is compatible with router.map, but not with the Router constructor

I'm experiencing an issue in my app where routes work fine when I use router.map({}) with the vue-router, but they fail to work when I pass them directly in the constructor. Any insight into why this might be happening? // Routes that work: const rou ...

Having trouble fetching API objects successfully

I've recently ventured into the use of the @nuxtjs/strapi package in combination with Strapi 4 and Nuxt 3. Unfortunately, I have found that this module is not well-documented, leaving me unsure about how to properly extract information from my API. He ...

Exploring the feature of setting the checked state in Radio.Group using Antd

I am dealing with dynamic data that needs to be displayed in a radio button format. One of the challenges is comparing the dynamically generated id with the active radio id and setting it as checked using Radio.Group. Unfortunately, the current code is no ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

Steps for including a path to a base64 encoded image

I am currently facing a challenge in embedding images into my emails where I need to encode them using an online tool. The issue I am encountering is that the email template I am using has a dynamic URL, with ${loginurl}/images as the path to my image. H ...