Utilizing the power of Vue.js and D3.js in tandem to create dynamic force simulations

Currently, I am attempting to retrieve data from a Restful API call and utilize it to create a d3.js force simulation. However, I have encountered an issue where if I use the data from the API call directly, the simulation treats it as if there is no data present. When I attempt to wait for the next tick using this.$nextTick(simu), all positions end up being represented as NaN. Is there a specific reason for this unexpected behavior?

const URL = 'https://jsonplaceholder.typicode.com/posts';

new Vue({
  el: '#app',
  data() {
    return {
      webGraph: {
        nodes: [],
        edges: []
      },
      graph1: {
        nodes:[
          {url:2},
          {url:3},
        ],
        edges:[
          {source:2, target:3},
        ]
      }
    }
  },
  created() {
    axios.get(URL).then((response) => {
      let node1 = {
        url: response.data[1].id
      }
      let node2 = {
        url: response.data[2].id
      }
      let edge = {
        source: {url:response.data[1].id},
        target: {url:response.data[2].id}
      }
      this.webGraph.nodes.push(node1)
      this.webGraph.nodes.push(node2)
      this.webGraph.edges.push(edge)
    })
    
  d3.forceSimulation(this.webGraph.nodes)
      .force("charge", d3.forceManyBody().strength(-25))
      .force("link", d3.forceLink().id(d => d.url).links(this.webGraph.edges))
      .on('end', function() {
        console.log("done")
      });
  d3.forceSimulation(this.graph1.nodes)
      .force("charge", d3.forceManyBody().strength(-25))
      .force("link", d3.forceLink().id(d => d.url).links(this.graph1.edges))
      .on('end', function() {
        console.log("done")
      });
  

  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h6>{{webGraph}}</h6>
  <br> 
  <h6>{{graph1}}</h6>
</div>

Answer №1

The reason webGraph and graphData1 produce different outcomes is due to the fact that the simulation of webGraph starts before it receives any data. Moving the simulation code inside the axios.get().then block will result in the expected behavior.

const URL = 'https://jsonplaceholder.typicode.com/posts';

new Vue({
  el: '#app',
  data() {
    return {
      webGraph: {
        nodes: [],
        edges: []
      },
      graph1: {
        nodes:[
          {url:2},
          {url:3},
        ],
        edges:[
          {source:2, target:3},
        ]
      }
    }
  },
  created() {
    axios.get(URL).then((response) => {
      let node1 = {
        url: response.data[1].id
      }
      let node2 = {
        url: response.data[2].id
      }
      let edge = {
        source: node1,
        target: node2
      }
      
      this.webGraph = {
        nodes: [node1, node2],
        edges: [edge]
      };
      
      d3.forceSimulation(this.webGraph.nodes)
        .force("charge", d3.forceManyBody().strength(-25))
        .force("link", d3.forceLink().id(d => d.url).links(this.webGraph.edges))
        .on('end', function() {
          console.log("done")
        });
    })

  d3.forceSimulation(this.graph1.nodes)
      .force("charge", d3.forceManyBody().strength(-25))
      .force("link", d3.forceLink().id(d => d.url).links(this.graph1.edges))
      .on('end', function() {
        console.log("done")
      });
  

  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h6>{{webGraph}}</h6>
  <br> 
  <h6>{{graph1}}</h6>
</div>

In your code, I also made a change to how edge is initialized. This highlights the importance of understanding the difference between variables and references.

By using

let edge = { source: {url:response.data[1].id}, target: {url:response.data[2].id} }
, any changes to node1 won't affect edge.source. On the other hand, with
let edge = { source: node1, target: node2 }
, if node1 changes, then edge.source will always reflect the latest value making the code more efficient.

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

Getting row data in datatables after a button click: A step-by-step guide

Could somebody provide assistance with retrieving a single row of data on a click event? This table is dynamically populated after the AJAX call's Success function is executed <div class="table-responsive table-wrap tableFixHead container-flu ...

What are the steps for performing a self-triggered AJAX post request?

I have been exploring self-invoked functions and recently used an http.get function to retrieve data from a JSON file like this: var Callmodule = (function(){ var urljsonEntrata= "modello.json"; function getmodules(){ var req = $.ajax({ url: ...

The issue with Vue Router is that it fails to display the intended component

I am facing an issue with nested routes in vue-router, specified in the router.js file. After logging in, the Query and Result links in the Header section always display the Register and Login components, even though my Vuex setup seems correct based on my ...

How can I achieve the same result as npm run start:ci with yarn?

I need help setting up Bitbucket CI/CD to run cypress tests on my vue app that utilizes yarn as its package manager. Is there a method to launch the server in the background using yarn? Appreciate any assistance. Thanks in advance! ...

Managing user logins across different sessions using passport.js, mysql database, and express-session

Currently, my app utilizes Passport.js for user authentication with Facebook, which is functioning properly. The issue arises when my node.js server is restarted and the users are automatically logged out. It appears that using express-sessions would be a ...

The download attribute in HTML5 seems to be malfunctioning when encountering a 301 Moved Permanently

I am attempting to create an automatic download feature for a file from a URL with a 301 Moved Permanently redirection. Here is the current code: <a href="myserverapi/download?fileId=123" download="image.jpg" target="_blank" ...

Iframe overlay feature functioning on Chrome but not on IE11

I have a Document viewer with a .less file containing the following styling: div.document-previewer-container { //height: 400px; //width: 300px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; //padding: 5px 2px; > div.document-preview { h ...

dual slider controls on a single webpage

I am attempting to place two different sliders on the same page. When I implement the following code for one slider, it functions correctly: <h3>Strength of Belief</h3> <div class="slidecontainer"> <div class="slider_left"> < ...

Trigger function in a different child component on mouse up

Trying to call a function in a child component from another child component in ReactJS. Specifically, I want to trigger a function in another component when the 'mouseup' event happens. Here is an illustration of what I am attempting to achieve: ...

I encountered difficulties rendering a VueJS component after incorporating the Argon Dashboard for Laravel into my project

I have a project that is currently active and all the VueJS components within it are functioning properly. However, after installing the Argon Dashboard for Laravel into my Laravel project, I am having an issue where my VueJs Components are not displayin ...

Toggle the mute and unmute feature for a participant in an AWS Chime meeting

Hello everyone! I'm looking for details on the AWS Chime SDK (amazon-chime-sdk-js). Is it possible with the Amazon Chime SDK for 3 participants (Anna, John, and Lenny) in a meeting room to have Anna ignore Lenny's microphone and only hear John, ...

Is there a way for me to view the properties within the subcomponents?

Working on a project to create a bulletin board using React, following the official documentation. Decided to consolidate all actions related to the bulletin board into one alert component called AlertC. In the Form onSubmit statement, if the title is tr ...

Tips for creating responsive content within an iframe

I have inserted a player from a website that streams a channel using an iframe. While I have managed to make the iframe responsive, the video player inside the iframe does not adapt to changes in viewport size. Despite trying various solutions found online ...

Exploring cookies to extract and display my email using Express.js

I am currently working on retrieving the name and value fields as cookies through a loop in my app.get method, then posting the field values in the app.post method using expressjs. I would appreciate it if someone could review the 'for loop' bel ...

Javascript/AJAX functions properly on the homepage, but encounters issues on other pages

For a client, I have recently created 4 websites using Wordpress. Each site includes a sidebar with a script that utilizes the Google Maps API to estimate taxi fares. Strangely, the script works perfectly on the home page of each site, but fails to funct ...

Determining the best use-case for a React framework like Next or Gatsby versus opting for Create React App

As I delve into the world of React and JavaScript, I find myself in the fast-paced prototyping stage. I can't help but ponder at what point developers choose to utilize frameworks like Next.js or Gatsby.js over the usual Create React App. I'm pa ...

The use of "Undefined in res.redirect" is a common issue that may arise when working with a combination of libraries such as

Encountering an issue while trying to redirect the user to a signature route with the file name as a URL argument, and receiving undefined... Example of a file as a URL argument after upload: http://localhost:3000/undefined?arquivo-assinado=82a35943-5796 ...

Getting the selected value from a dropdown menu in ReactJS

I am working on creating a form that resembles the following structure: var BasicTaskForm = React.createClass({ getInitialState: function() { return { taskName: '', description: '', emp ...

The property 'enabled' is not a standard feature of the 'Node' type

Within the code snippet below, we have a definition for a type called Node: export type Node<T> = T extends ITreeNode ? T : never; export interface ITreeNode extends TreeNodeBase<ITreeNode> { enabled: boolean; } export abstract class Tre ...

Calculate the total sum of selected values in a multiple select dropdown using jQuery

Is there a way to calculate the sum of selected items in a multiple selection dropdown menu? For instance, if I select "X12SO" and "X13SO", their values should add up to 30. let total = 0; $("select[name='myselect[]'] option").each(function(){ ...