The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this:

data(){
    return{
      test: test_data,
      nodes:{},
      edges:{},
      nextNodeIndex: Number,
      selectedNodes: ref<string[]>([]),
      selectedEdges: ref<string[]>([]) 
    }
  }

and here are my defined methods:

methods: {
    g(){  
      this.nodes = reactive(this.test.nodes)
      this.edges = reactive({ ...this.test.edges })
      console.log(this.nodes)
      console.log(this.edges)

      this.nextNodeIndex = ref(Object.keys(this.nodes).length + 1)     
    },
    addNode() {
      const nodeId = this.nextNodeIndex.value 
      this.nodes[nodeId] = {
        name: String(nodeId),
        size: 16,
        color: "blue",
        label: true
      } 
      this.nextNodeIndex.value++ 
      console.log(this.nextNodeIndex)
    },
    removeNode() {
      for (const nodeId of this.selectedNodes.value) {
        delete this.nodes[nodeId] //Delete the selected node, by their ID
      }
    },

However, I encountered an error when attempting to remove a node which stated

this.selectedNodes.value is not iterable
. How can I properly define selectedNodes then?

The provided link includes an example of removing edge functions using the library. While I followed the same approach, I prefer to implement the function within a method as part of my Vue project. Being relatively new to Javascript and Vue, any advice or suggestions would be highly valued.

Answer №1

Your provided example utilizes the OptionsAPI data function to generate reactive state, while the guide you are referencing employs a Script setup that necessitates the use of the ref() function for creating reactive variables.

Since data already produces reactive object state, using ref within it is unnecessary, and its properties can still be accessed via dot notation without requiring value.

In your specific scenario, it would be advisable to make the following modification:

for (const nodeId of this.selectedNodes.value) {

To

for (const nodeId of this.selectedNodes) {

Additionally, you can update the two specified properties in data:

selectedNodes: ref<string[]>([]),
selectedEdges: ref<string[]>([])

With

selectedNodes: [],
selectedEdges: []

I trust this guidance proves helpful to you!

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

Having trouble sending data from the controller to the view in Laravel 8

I am struggling to display data retrieved from the database in my view through the controller. Despite trying various solutions found on similar questions, none of them seem to be effective. My main goal is to showcase a list of employees on my admin page. ...

Verification of unique custom string

How can I ensure that a string follows the specific format of x.xx.xxxxx? The first character is mandatory, followed by a period, then two characters, another period, and finally any number of characters of varying lengths. ...

Immersive pop-up interface displaying a variety of embedded videos simultaneously

I am a beginner in JavaScript and I came across a CodePen that does exactly what I need, but it currently only works for one embedded video. What I aim to achieve is similar functionality, but with 6 videos. (function ($) { 'use strict'; ...

Transferring files via Bluetooth on PhoneGap

As someone new to phonegap, I'm interested in transferring text files from one device to another using Bluetooth within the platform. I've looked at several examples but haven't found a solution yet. I've come across some examples that ...

Demonstrate JSON data using ngFor loop in Angular

Need some assistance here. Trying to display data from a .json file using a ngFor loop. However, I keep running into the following error in my code: Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgF ...

Validation of emails in Angular through the utilization of reactive forms

Hello there, I'm new to Angular and looking for some assistance. Specifically, I am currently working on validating an email input using a reactive form with the keyup event. registerform:any; ngOnInit(): void { this.registerform = new F ...

Unable to send a post request using ajax

Section of Form in home.php <div id='googleForm'> <form> <div class='item'> <label class='label'>Full Name</label> <input class=&apos ...

Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been ...

Ways to convert field data to lowercase in MongoDB query result

I have two Objects in my database collection. [ {"_id" : 1, name: "notLowercased"}, {"_id" : 2, name: "lowercased"}, ] Using find and $regex to search for names that include a specific string. data = await Catal ...

Is it possible to streamline multiple $.fn. calls using javascript or jQuery?

I recently started using datatables and was advised to include the following code: $.fn.dataTableExt.oStdClasses.sWrapper = 'no-margin last-child'; $.fn.dataTableExt.oStdClasses.sInfo = 'message no-margin'; $.fn.dataTableExt.oStdClasse ...

Sharing state between components in NextJS involves using techniques like Context API, passing

I am trying to pass state between pages in Next.js. In my App.js, I have wrapped it in a context provider like this: import { useRouter } from 'next/router' import { ClickProvider } from '../context/clickContext' function MyApp({ Compo ...

When rendering, DirectionsRenderer replaces the Marker

I'm currently working on implementing a real-time tracking system for customers to track their deliveries. I have succeeded in setting up markers for the destination and pickup locations, as well as a route path towards them. However, I encountered an ...

Guide to managing MUI's theme typography font weight choices with TypeScript

I am interested in learning how to incorporate a new font weight into my theme, for example, fontWeightSemiBold, and disable the existing fontWeightLight and fontWeightMedium. I believe this can be achieved through module augmentation. For reference, there ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Transmitting a Wav file from JavaScript to Flask

I'm currently working on a JavaScript code that records audio from the browser and now I need to figure out how to send it back to Flask. start: function () { var options = {audio: true, video: false}; navigator.mediaDevices.getUserMedia(optio ...

Troubleshooting a TypeScript error when trying to access an imported service in Angular 2

I've been working on creating a form that allows users to input required details, which will trigger a server call and save the information. However, no matter what I try, I keep encountering the following error: ORIGINAL EXCEPTION: TypeError: this.po ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

Using JS or jQuery to organize JSON data into a multidimensional array

Dealing with frontend processing of a response from a server that provides event reviews for the season has been challenging. In this case, there can be multiple reviewers for the same event and the simplified version of the response appears as follows: [ ...

Create a Vue component that utilizes the v-for directive to iterate through a list of items, passing data from a

Imagine having two arrays with a similar structure like this: const individuals = [{name: "Jane Doe", id: "0001"},{name: "John Doe", id:"0002"}, {name: "Sam Smith", id: "0003"}, {name: "Joe ...