It is my first time working with Websockets and I'm struggling trying to get a property from the websocket message and pass it to the state of my application. I'm connecting to the websocket just fine, getting the data from the websocket and pass it to a variable but then I realize that when I try to pass that data to a state property it won't update on real time.
All the following code is on the App.vue file:
I'm just using a button to test the websocket connection and then sending a message to parse the websocket payload:
<section id="Websocket" class="mt-6">
<h2 class="text-2xl font-bold mb-2 text-gray-700">
Testing The Rubiko Websocket
</h2>
<BaseButton
buttonType="btnPrimary"
v-on:click="sendMessage('Hello World')"
>Send Message</BaseButton
>
</section>
Then on the App in vue I have the websockect connection (connection) and the connectionId (this is the id that I'm trying to get from the websocket):
data() {
return {
connection: null,
connectionId: '',
}
},
Then on the vue created lifecycle hook I implement the connection to the websocket like this:
created() {
console.log('Starting connection to WebSocket Server')
this.connection = new WebSocket('wss://ws.xxxxx.io')
const v = this
this.connection.onopen = function (event) {
console.log(event)
console.log(
'Successfully connected to the Websocket server...'
)
}
this.connection.onmessage = function (event) {
console.log(event)
let jsonObject = JSON.parse(event.data)
v.connectionId = jsonObject.connectionId
}
},
I had problems with the "this" scope inside the this.connection.onmessage function, hence the:
const v = this
So with v.connectionId = jsonObject.connectionId I'm trying to pass that data from the websocket to my app state, and this is not working or at least not working as expected.
What happens is I can see all the logs and everything working fine (Handshake, etc), but when I check the application state with the Vue devtools the "connectionId" property on the state applications is not being update in real time BUT (and this is really weird to me) whenever I click the App component on the devtools then the "coonectionId" property updates.
I click the button, the state property won't update:
Then when I click "App" on the devtools it will immediately update the value:
Will really appreciate any help.