Strategies for refreshing the graph when a new user enters the Vue.js chat room

After creating a graph, I face the issue of keeping it static when new users join the chat. Even though the this.users object gets updated with each new user, the graph remains unchanged. Is there a way to automatically redraw the graph every time a new user is added to this.users?

<template>
  <div>
    <svg width="290" height="500" class="container-border"></svg>
  </div>
</template>
<script>
import * as d3 from "d3";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {};
  },
  computed: {
    ...mapState(["user", "users"]),
  },
  methods: {
    getUser(key) {
      let nodes1 = [];
      let edges1 = [];
      let obj = [{ nodes: nodes1 }, { edges: edges1 }];
      const names = Object.values(this.users);
      let i = 0;
      names.forEach((item) => {
        nodes1.push({ name: item.name });
        edges1.push({ source: 1, target: i, relation: "", value: 0.5 });
        i++;
      });
      return obj;
    },
  },
  mounted() {
    let marge = { top: 5, bottom: 5, left: 5, right: 5 };
    let svg = d3.select("svg");
    let width = svg.attr("width");
    let height = svg.attr("height");
    let g = svg
      .append("g")
      .attr("transform", "translate(" + marge.top + "," + marge.left + ")");

    let resultGraph = this.getUser();
    let nodes = resultGraph[0].nodes;
    let edges = resultGraph[1].edges;

    let colorScale = d3
      .scaleOrdinal()
      .domain(d3.range(nodes.length))
      .range(d3.schemeCategory10);

   ...
  },
};
</script>
<style scoped>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Your assistance in solving this issue would be greatly appreciated!

Access the full code on CodePen

Answer №1

The issue lies in not refreshing the chart after updating the users.

Resolution

Segment your d3 chart code into distinct lifecycle functions. The init function establishes the static components of the chart, such as scales and group elements. The update function accepts the data and displays the dynamic aspects of the chart, like links and link texts. Utilize join instead of enter in the render function for efficient re-rendering. Consider including a destroy function to eliminate lingering event listener references. Perhaps employ a class to encapsulate your chart.

Execute the init function during component mounting.

Add a watcher on your Vue component that triggers upon updates to the users property. Call the render function each time the watcher is activated, passing in the users.

To delve deeper into the d3.js join function, refer to: https://github.com/d3/d3-selection/blob/v2.0.0/README.md#selection_join

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

Anticipate the occurrence of an event in Node.js

Is there a way to wait for an event in node js? In my bpmn workflow development, I need to execute the events step by step. Each script represents an event within the server that consists of multiple scripts. For example: 'use strict'; const Bpm ...

The timepicker is set to increment by 30-minute intervals, however, I would like the last time option to be 11:

I am currently using a timepicker plugin and am trying to set the last available time option to be 11:59pm. Despite setting the maxTime attribute in my code, the output does not reflect this change. Any suggestions on how to achieve this would be highly ap ...

Passport Authentication does not initiate a redirect

While working on a local-signup strategy, I encountered an issue where the authentication process against my empty collection was timing out after submitting the form. Despite calling passport.authenticate(), there were no redirects happening and the timeo ...

Preserve page configurations upon page refresh

I'm currently in the process of creating a 'user settings' form. Each list item represents a different section, such as Updating username, Updating email, and Changing password. It looks something like this: <li> <header>Ti ...

Retrieve the parameter values in PHP that were passed from AngularJS

This is my first time working with PHP and AngularJS. I am trying to pass parameters from AngularJS to a PHP file, where they will be used in an INSERT query. I have set up an XMLHttpRequest to call the PHP file (addsubscriber.php?par1=val1&par2=val2) ...

What is the method to have text added automatically to an input field when a key is pressed?

Within my navigation, I have implemented a "full-screen overlay search box". When users click on the magnifying glass icon, a full-screen overlay with a search input field appears. You can see an example image here: . Currently, to enter text in this full ...

jquery add to table id, not to a table within

Having trouble adding a table row to a specific table ID without it appending to other tables with different IDs nested inside. I've searched for a solution but can't seem to find one. Can someone help me figure out what I'm doing wrong? Her ...

"The AJAX response returned a status code of 200, however, the PHP script being executed on the XAMPP localhost did not provide

The HTML code initiates a localhost function called getNodes which returns JSON data that is verified by JSON lint. However, when the same function is invoked using AJAX from a JavaScript file, a 200 response code is received without any response data. I h ...

Ways to display the page's content within a div container utilizing Jquery

I am attempting to display the content of a URL page (such as ) within a <div> using JQuery, but so far I have been unsuccessful. Here is an example of what I am trying to achieve: <div id="contUrl"> .. content of google.fr page </div> ...

Error in ReactJs: Attempted to access the property 'map' of an undefined value

Facing an issue with a "TypeError: Cannot read property 'map' of undefined" message. I am new to React, so I'm uncertain about what's causing the error. The problem arises when trying to call this.props.meals.map export class Dashboard ...

Is there a quicker method to completely replace an element's DOM with another in jQuery?

Currently, I am utilizing jQuery's AJAX functionality to retrieve new content from the server in JSON format: $.ajax({ url: url, data: { 'ajax': '1', }, dataType: 'json', success: somefunction ...

Stop ngOnChanges from being triggered after dispatching event (Angular 2+)

In Angular 2+, a custom two-way binding technique can be achieved by utilizing @Input and @Output parameters. For instance, if there is a need for a child component to communicate with an external plugin, the following approach can be taken: export class ...

Seeking assistance with Shopify - Enhancing User Experience with Javascript Cookies

Is there a way to adjust the settings of how long Shopify stores cookies on your computer for? Currently, it retains cart information for two weeks. Any suggestions on how to modify this? I am considering two possibilities: 1) Making shopping members-only ...

Accessing the user's referral URL in Express.js when they submit a post

I am looking to implement a commenting system on my website, and I need to capture the page information where the comment is being made (such as a specific video uploaded by a user) in order to save it in the database. The route structure is set up like t ...

I aim to combine a few variables of uncertain types within a string

When using concatenation with pluses, it could potentially result in unexpected outcomes. My desired result is 123. var one = 1; var two = 2; var three = '3'; var result = one + two + three; alert(result);//I want-> 123 ...

Some inquiries regarding the fundamentals of JavaScript - the significance of the dollar sign ($) and the error message "is not a function"

Teaching myself JavaScript without actually doing any explicit research on it (crazy, right?) has led to a few mysteries I can't quite crack. One of these mysteries involves the elusive dollar sign. From what I gather, it's supposed to be a con ...

Using vue.js to assign data within an if statement of a function

I have a Vue form that is set up like this: new Vue({ el: '#login-container', data: { firstname: '', lastname: '', email: '', ...

Step-by-step Guide on Utilizing Bootstrap Table

Currently, I am in the process of fetching data from an API and displaying it in a tabular format using JavaScript. While I have successfully retrieved the data, I'm facing an issue with applying Bootstrap styling to the table headers. async functi ...

ReactJs dropdown menu without preset option

Currently diving into the world of reactJs and experimenting with react-select. Here's how my html is structured: <div class="col-md-2"> <div class="well"> <h1>h1</h1> <div id="c ...

Animating nested ng-repeat loops

Trying to animate a list of elements divided by rows (the parent ng-repeat) and columns (the child ng-repeat) has been quite challenging. While I was able to achieve the desired animation with individual ng-repeats, the same cannot be said for nested ng- ...