How to update my Vuex store for a message in a messageSet

Viewed 42

I am trying to use vue-socket.io to create a chat application. So far I've figured out how to set up the socket to create rooms and such but now I am trying to make messages show between chats and update the Vuex store to show messages as I flip back and forth between the different channels.

I am having an issue figuring out how to update my Vuex state with the message. The socket server emits a message to a room that is based on a v_code that which is included in the message.

Here is my socket on message code

message(message) {
        if(this.conversation.v_code == message.v_code) { // This checks to make sure just the active view is sent the message
            let userID = this.$store.getters.userID
            userID = userID.cognitoUsername
            if(message.userID === userID) message.fromMe = true
            this.displayMessages.push(message) // This is where the active view messages are seen/rendered from
        }
    }

The data structure of state.messages

{
  {
    {
      v_code: <token>,
      messages: [] <-- array of messages for this v_code
    }
  }

}

So what I am trying to figure out is how I can update state for the correct messageSet (that is what I have been calling the array of messages). I just want to push the new message to the array in the messageSet but only for the correct messageSet. I have tried using the find method but have had no luck. Here is the find that I am assigning to displayMessages when changing channels/rooms.

this.messages.find((messageSet) => messageSet.v_code === message.v_code)

How can I do what I want? I assume some version of the find method but not sure the exact way.

1 Answers

I have figured it out, I changed my socket on message to remove the display messages update and instead now use a Vuex action and mutation. I was close with the find part and just needed to change it so it pushed to the state. I was surprised to see it push it directly to the state using a find method.

The result was this line was needed in the mutation

state.messages.find((messageSet) => messageSet.v_code === message.v_code).messages.push(message)
Related