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 ?
from Vuex + Websocket native: Getting Async State from Websocket within module action
No comments:
Post a Comment