Lou Süsslin
Lou Süsslin

Reputation: 559

How does one get an active instance of socket.io?

io.on('connection', socket => { })

This snippet gives you instance 'socket', but I am currently in need of using that instance somewhere else in my project.

Is there a way of accessing it by the port it's running on or similar?

I am trying to change the state in Vuex (Vue.js) with Sockets, which I'd put into a handler in a REST Api.

Upvotes: 0

Views: 97

Answers (1)

Hammerbot
Hammerbot

Reputation: 16354

As Reiner stated in his comment, you can try to save the socket into vuex itself in order to access it from all of your project. For example:

new Vue({
    ...
    created () {
        io.on('connection', socket => {
            this.$store.dispatch('SET_SOCKET', {
                getInstance () {
                    return socket
                }
            })
        })
    }
})

Don't forget to define the 'SET_SOCKET' actions and mutations.

You will then be able to access it using this.$store.state.socket.getInstance()

I use getInstance() because if I remember correctly the socket mutates itself over time, and VueX does not like that.

Upvotes: 2

Related Questions