Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
Vuex + Websocket native: Getting Async State from Websocket within module action

I'm trying to populate data using the rootstate from a state coming from a websocket in an action like this:

export const actions = {
    fetchChats({ commit, rootState }) {
        const data = rootState.websocket.incomingChatInfo
        commit('SET_CHATS', data)
    },
}

The thing is that since the websocket module is asynchronous websocket.incomingChats is not there yet when the fetchChats action is called on the created cycle method of the component.

created() {
    this.$store.dispatch('chatQueue/fetchChats'), null, { root: true }
}, 

This is the websocket store async action:

export const actions = {
    processWebsocket({ commit }) {
        return new Promise((resolve) => {
            const v = this
            this.ws = new WebSocket('xyz')
            this.ws.onopen = function (event) {
                commit('SET_CONNECTION', event.type)
                v.ws.send('message')
            }
            this.ws.onmessage = function (event) {
                commit('SET_REMOTE_DATA', event)
                resolve(event)
            }
            this.ws.onerror = function (event) {
                console.log('webSocket: on error: ', event)
            }
            this.ws.onclose = function (event) {
                console.log('webSocket: on close: ', event)
                commit('SET_CONNECTION')
                ws = null
                setTimeout(startWebsocket, 5000)
            }
        })
    },
}

And this is the mutation thats been called when the promise is resolved:

SET_REMOTE_DATA(state, remoteData) {
    const wsData = JSON.parse(remoteData.data)
    if (wsData.connectionId && wsData.connectionId !== state.connectionId) {
        state.connectionId = wsData.connectionId
        console.log(`Retrieving Connection ID ${state.connectionId}`)
    } else {
        state.messageType = wsData.type
        state.incomingChatInfo = wsData.documents
    }
},

Is there any way I can make const data = rootState.websocket.incomingChats wait until the websocket promise is resolved and I know for sure that there's data to get from the websocket module ?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Any actions that depend on processWebsocket should happen after its completion, i.e. a promise should be chained:

  mounted() {
    await this.$store.dispatch('processWebsocket')
    await this.$store.dispatch('fetchChats')
  }

If they occur in different components, a component that uses fetchChats on mount shouldn't be mounted until the completion of processWebsocket.

It's a mistake to assign data to this, which is Vue instance of Vuex store, it's not guaranteed to exist and shouldn't be used to hold random data. Instead, ws needs to be commited to the store as any other data.

about 4 years ago · Juan Pablo Isaza Denunciar

0

you can try using Vuex async and await.

export const actions = {
    async fetchChats({ commit, rootState }) {
        const data = await rootState.websocket.incomingChatInfo
        commit('SET_CHATS', data)
    },
}

then in your created() hook.

created() {
    await this.$store.dispatch('chatQueue/fetchChats'), null, { root: true }
},

You might probably has to add async and await to your processWebsocket action also.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda