Error encountered while trying to connect to WebSocket: InvalidStateError

After setting up a basic Vue project with the vue-cli tool using vue init webpack my-project, I encountered an issue with sending information through a web socket before the page renders. To keep this logic separate from the Vue component, I created a separate JavaScript file named ws.js. Here's the code snippet based on this:

import Vue from 'vue'

const websocket = new WebSocket('ws://localhost:1234')

const emitter = new Vue({
  name: 'emitter',
  methods: {
    send (message) {
      websocket.send(JSON.stringify(message))
    }
  }
})

export default emitter

When attempting to utilize the emitter object to transmit information upon page load in my Vue component:

<template>
    <div class="hello">
      TEST
    </div>
</template>

<script>
import emitter from '../ws/ws'
export default {
  name: 'HelloWorld',
  beforeMount () {
    emitter.send('Hello')
  }
}
</script>

An error surfaced in the Firefox console:

[Vue warn]: Error in beforeMount hook: "InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable"

found in

---> at src/components/HelloWorld.vue at src/App.vue

I'm puzzled by this error. Is my approach correct? Should I consider attaching the functionality to a different event listener rather than beforeMount()? Interestingly, when I disable the WebSocket related lines, the error vanishes:

import Vue from 'vue'

// const websocket = new WebSocket('ws://localhost:1234')

const emitter = new Vue({
  name: 'emitter',
  methods: {
    send (message) {
      // websocket.send(message)
    }
  }
})

export default emitter

Answer №1

Prior to sending any messages, it is essential for the socket to be in a ready state. Taking inspiration from this helpful answer, I made modifications to the file ws.js:

import Vue from 'vue'

const websocket = new WebSocket('ws://localhost:1234')

// Ensure that the function waits for the connection to be established...
function waitForSocketConnection (socket, callback) {
  setTimeout(
    function () {
      if (socket.readyState === 1) {
        console.log('Connection established')
        if (callback != null) {
          callback()
        }
      } else {
        console.log('Waiting for connection...')
        waitForSocketConnection(socket, callback)
      }
    }, 5) // wait time of 5 milliseconds for the connection...
}

function sendWaiting (msg) {
  waitForSocketConnection(websocket, () => {
    console.log('Sending message: ' + msg)
    websocket.send(msg)
    console.log('Message sent: ' + msg)
  })
}

const emitter = new Vue({
  name: 'emitter',
  methods: {
    send (message) {
      sendWaiting(message)
    }
  }
})

export default emitter

The application now verifies the readiness of the WebSocket before dispatching any messages. If not ready, it continuously rechecks every 5 milliseconds until it becomes available.

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

Steps for inserting a video into a new div upon selecting a hyperlink

Looking for a way to link menu elements to corresponding videos in adjacent divs? I have two divs set up - one with the menu list and another right next to it where the videos should be loaded. Forms seem like a potential solution, but I lack expertise i ...

Are there any available polyfills for downloading links using data URIs?

My issue involves generating code from the server: <a download="test.csv" href="data:text/plain;charset=utf-8;base64,w4FydsOtenTFsXLFkXTDvGvDtnJmw7p0w7Nnw6lwLg=="> teszt </a> This solution currently works with Chrome, Firefox, and Opera. ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

What is the reason for my form data not being saved in the database?

Here is all the code in my app.js file: var express = require("express"); var app = express(); var port = 3000; app.listen(port, () => { console.log("Server listening on port " + port); }); var mongoose = require("mongoos ...

MQTT Broker specialized in Typescript

I'm looking to create a MQTT Broker using TypeScript and Angular. I've attempted a few examples, but I keep encountering the following error: Uncaught TypeError: http.createServer is not a function Here's a simple example of what I'm c ...

A guide on seamlessly connecting props with local data using 2-way binding in Vue 3

Seeking guidance on binding a component's prop to its own data property. Let's say we have a component named ModalComponent <template> // ModalComponent.vue <div v-if="showModal"> ... <button @click=" ...

Implementing pagination within nested ng-repeat in Angular app

I am currently utilizing Angular along with the Material library in my project. I am facing an issue with two nested ng-repeat loops within md-tables. The problem lies in the fact that the variable is getting overridden with each request in the nested loop ...

Manipulating the actual DOM in ReactJS to display a formatted number or string while preserving its original value

Hello, I am new to ReactJS and currently using it along with ReactDataGrid. I am trying to figure out how to change the real DOM value of a specific cell in the table. Here is the table I am working with: https://i.sstatic.net/CAcSH.png My goal is to cha ...

Implementing Firestore Read Limitations in a React Application

I have encountered an issue with Firebase billing based on the number of document reads. There is a daily limit of 50k reads per day in Firestore, but when I try to fetch documents in my React app, it triggers a quota exceeded error. FirebaseError: Request ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

OBJLoader encountered an unexpected line: "<!DOCTYPE html>" while using vue cli3

Utilizing the vue-3d-model component for a 3D object viewer in cli3 has presented a challenge that needs to be addressed. <script> // import { ModelThree } from 'vue-3d-model' import { ModelObj } from 'vue-3d-model' ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Choose all div elements with a specified class from a variable

How can I retrieve all div elements with the "test" class from a variable and insert them into another div? var response = xmlhttp.responseText; var selectedDivs = $(response).find('.test'); $('.anotherdiv').prepend(selectedDivs); ...

Unable to retrieve Google Maps route on Android device

After discovering the route between two latitude and longitude values on Google Maps using "Get Directions," everything appears accurately. However, when attempting to use the same directions in an Android mobile application, only the destination marker ...

Having trouble with your onclick event not firing? Utilize jQuery to troub

Struggling to convert a hover trigger to a click event, but for some reason, no click function seems to work? Here is the current code that functions on hover... Current Working Code for Hover... $showSidebar.hover(function() { $wrapper.stop ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...

"The webpack-dev-server seems to be failing to forward requests to an external domain using the proxy

I'm currently facing an issue with setting up the webpack-dev-server proxy configuration to route api requests to an external domain. Despite my efforts, I am unable to get it to function properly. Below is my configuration: var path = require(&apos ...

JavaScript still mentions a class that no longer exists

One of my elements has a class of .collapsed. When this element is clicked, a jQuery function is triggered to remove the .collapsed class and add the .expanded class instead. Even after the .collapsed class is removed, the function I have created continue ...

Guide to Incorporating a Marker into an SVG Blinking Rectangular or Circular Border Image on Google Maps

I have a link that points to a specific location on Google Maps using latitude and longitude: http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png Now, I am looking to add a blinking border to this marker link. Is there a way to achieve this ...

Can someone help me troubleshoot the issue with my submit button's onclick function?

I am currently working on a project where I have a content box enclosed in a div tag. Within this content box, there are paragraphs with unique IDs for individual styling rules. I have set margins, padding, and other styles accordingly. At the bottom of th ...