Template in VueJS not updating as expected when returning array data

For my current project, I am implementing a chat system using VueJS and socket.io for interactions between admins and clients. However, I am facing an issue where adding a new row in the admin chats with the client's name upon connection and removing it when they disconnect is not functioning properly. It seems that even after a user disconnects, the chat remains visible until I manually reload the page.

Here is a snippet of my template:

    <div class="chats" id="chat"  v-if="chats.length >= 1">
        <div class="chat" v-for="chat in chats">
            <b>{{ chat.clientName }}</b>
            <p>ID: {{ chat.clientID }}</p>
            <div class="jens-button">
                <img src="/icons/chat-bubble.svg">
            </div>
        </div>
    </div>
    <div class="chats" v-else>
        <div class="chat">
            <b>There are no chats available.</b>
        </div>
    </div>

And here is a portion of my data and method setup:

        data() {
            return {
                chats: [],
            }
        },


        method() {                                           
            socket.on('update clients', (clients) => {
                console.log(clients);
                this.chats = [];
                if(clients.length >= 1) {
                    this.chats = clients;
                } else {
                    this.chats = [];
                }
            });
        }

I am seeking assistance in identifying what might be causing this malfunction in my chat system. Any insights or explanations would be greatly appreciated. Thank you!

Answer №1

Your current method of declaring methods in Vue is not valid. This means that your socket.on is never properly declared. It's recommended to use the mounted() hook instead. You can learn more about component lifecycles here.

An example would be as follows. Also, remember to include a :key for your v-for loop.

<div class="chats" id="chat"  v-if="chats.length >= 1">
        <div class="chat" v-for="chat in chats" :key="chat.clientID">
data() {
  return {
    chats: [],
  }
},
mounted() {
  socket.on('update clients', (clients) => {
    console.log(clients);
    if(clients.length >= 1) {
      this.chats = clients;
    } else {
      this.chats = [];
    }
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Order an array in Javascript based on the day of the month

I am trying to create a unique function that changes the order of a string based on the day of the month. For instance, if the input string is "HELLO" and today's date is the 1st of April, the output should be "LHEOL". On the 2nd of April, it should ...

Unraveling the mysteries of interpreting the jsben.ch benchmark results

After testing three fibonacci algorithms on jsben.ch, it's clear that the first one is the fastest and even received an award icon: https://i.sstatic.net/ilfDz.png However, I'm curious about the numbers next to the code block results. What do t ...

The jQuery code functions smoothly on computers, but experiences delays when running on an iPhone

I was working on my website and trying to add a div that sticks to the top of the browser when it scrolls out of view. I found a script that works well on desktop, but when testing it on iPhone, there is a slight delay before the div pops back up in the ri ...

Instructions on keeping a numerical counter at its current value for all site visitors

Recently, I integrated a number counter into my website. However, I am facing an issue where the count resets to zero whenever a new visitor accesses the site. I'd like the count to remain persistent and update based on the previous count. For instanc ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

Ways to conceal the label without using JavaScript when focusing

I am trying to find a way to hide the label "phone number" when the input is in focus by simply clicking on it. I have attempted using CSS but I need a more effective solution. Please let me know if you can help. <div class="form-row"> ...

Ensuring button is inactive when API value is zero in Vue

Presented here are a set of buttons that provide live probability odds for a particular event, allowing users to make selections based on the updated data fetched from an API every minute. https://i.stack.imgur.com/uGdld.png If the probability displayed ...

Most Effective Method for Directing Users to Mobile Website

How do you prefer to guide users to a custom mobile site, such as redirecting from mysite.com to m.mysite.com or mysite.com/m? I previously experimented with the Detect Mobile Browsers JS solution, which seemed promising. However, I noticed that it initia ...

What is the best way to halt the current event handler thread's execution when another event is triggered that calls the same handler at

One of the functions in my code filters and sorts contents of a select dropdown based on input text entered by the user. The function filterSort() is triggered on each keyup event from the input field. Code $(inputTextField).keyup(function() { / ...

What is the most effective method for declaring a constant within a WebComponent?

After receiving questions, I included more details on how I'm utilizing the constants. The main issue I am encountering is that the constants are being added to the global object, which raises concerns about potential name collisions. I created a Web ...

How can I iterate through multiple rows in JavaScript?

Feeling stuck, the simple yet dreaded for loop has become my nemesis and I could really use some guidance. Currently, I have a Google sheet with 3 rows (excluding headers) and 8 columns. As users input data via a web app, the number of rows will dynamicall ...

Extracting graph coordinates from a webpage using web scraping

Looking for assistance with web scraping to extract player rankings from a graph displayed in this link Simply visit the link, click on Rating, and hover over the plotted points. The y-coordinate will be visible along with other relevant information that ...

Utilize the $.each method to incorporate a value to an outside variable

Within my codebase, I handle an Array of Strings by utilizing the following function: $.each(lines, processLine); The challenge I faced was that while the processLine function returns a string, I needed to merge all the strings into one final result. How ...

What is the best way to vanish the circles using keyboard commands?

After reviewing the example at http://bl.ocks.org/d3noob/10633704, my goal is to create an input field on my keyboard where I can enter a number, and then use array.slice() to make circles disappear based on that number. Unfortunately, my implementation ...

Unexpected twist observed when custom curve is applied to Threejs TubeGeometry

After creating a custom curve applied to TubeGeometry, I noticed an interesting behavior. The curve's vertices on the X axis change based on mouse movement, while the Z axis follows a simple sin curve affected by time. The code snippet below demonstra ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

How can we retrieve data from an endpoint using a Vuex action and then store the data in Vuex variables?

I am currently facing an issue where I need to retrieve data from an endpoint and then store that data in state variables within the app's store. The snippet of code I have written for this functionality is as follows: import Vue from 'vue' ...

Simulation was designed to be executed on a single node, but none was discovered during the process

Having trouble understanding why the onChange function is not being called. I have added an id but it seems unable to locate the element. File.test.js it("expects onChange event to be triggered on renderToDropdown ", () => { baseProps.onChange.moc ...

Angular2 - Working with form elements within form elements

I'm currently working on a project that involves dynamically adding and removing form elements. You can check out an example I’m following at this link. In the HTML file, I encountered a warning message regarding the 'filters' identifier ...