Md. Jahidul Islam
Md. Jahidul Islam

Reputation: 316

create socket instance from vuex

I am using vue socket io for getting data from socket. For getting data I use query like

// ioinstance
import io from 'socket.io-client'
const restaurantId = localStorage.getItem('restaurant-id')
const socketUri = process.env.SOCKET_URI

export default io(socketUri, {
  transports: ['websocket'],
  query: `channel_id=restaurant-${restaurantId}`,
  reconnect: true,
  reconnectionDelay: 500,
  reconnectionDelayMax: 1000,
  pingInterval: 200

})

Here I get restaurantId after i successfully logged in to the panel and dispatch an action after successfully logged in like

// from vuex module
import VueSocketio from 'vue-socket.io-extended'
import ioInstance from '../../socket-instance'
...
...
socketInitialize ({dispatch}) {
    let restaurantId = await localStorage.getItem('restaurant-id')
    if (restaurantId && restaurantId != null) {
      Vue.use(VueSocketio, ioInstance)
      this._vm.$socket.on(`restaurant-${restaurantId}`, (data) => {
        dispatch('socketIncoming', data)
      })
    }
  }

but creating vue instance is not working from socketInitialize action although create instance from vue component is working fine

// from component
import Vue from 'vue'
import VueSocketio from 'vue-socket.io'
import ioInstance from './socket-instance'
...
...
mounted () {
let restaurantId = await localStorage.getItem('restaurant-id')
if (restaurantId && restaurantId != null) {
    Vue.use(VueSocketio, ioInstance)
    this.$socket.on(`restaurant-${restaurantId}`, (data) => {
    this.$store.dispatch('socketIncoming', data)
    })
  }
}

Since I have to pass restaurantId for socket instance, I didn't initialize it from main.js (it renders first and restaurantId is not available here if not logged in) file. I need some suggestion, how could i create this initialization after logged in and any alternative way for initializing using Vue.use or this._vm or (new Vue()) or Vue.prototype

Upvotes: 0

Views: 1630

Answers (1)

User 28
User 28

Reputation: 5158

From Vue.use(plugin):

This method has to be called before calling new Vue()

So you have to register the plugin first then open the connection after when you ready. This question is already answered in FAQ section from the vue-socket.io-extended How to prevent connection until authed?.

Basically you have to tell socket.io to not open the connection at instantiate by set autoConnect to false:

const socket = io({
  autoConnect: false
})

Then when you ready call open function:

this.$socket.io.opts.query = `channel_id=restaurant-${restaurantId}`
this.$socket.open()

Upvotes: 2

Related Questions