What is the best way to modify the values in an initialized array once the fetchData method has been executed?

As a beginner in Vue.js, I am currently working on a project that involves updating initialized arrays in the data() section of my component using the fetchData method. Below is a simplified version of the code:

<script>
  import axios from 'axios';
  import Footer from '@/components/Footer'; 
  import Sidebar from '@/components/Sidebar'; 
  import BarChart from '@/components/ChartJS/Barchart';
 

  
  export default {
    name: 'Dashboard',
    components: {
      Footer,
      Sidebar, 
      BarChart,
     
  
    },
    data() {

  const data1 = [];
  const data2 = [];
  const data3 = [];
  const data4 = [];
  const data5 = [];
  const data6 = [];

//I need to update the data processed in the fetchData method here

  const data1Count = data1.length;
  const data2Count  = data2.length;
  const data3Count  = data3.length;
  const data4Count = data4.length;
  const data5Count = data5.length;
  const data6Count = data6.length;
      return {

    Cluster: {
        labels: ['Data 1', 
                  'Data 2', 
                  'Data 3',  
                  'Data 4',
                  'Data 5', 
                  'Data 6',
                 ],
         values: [data1Count , data2Count  , data3Count  , data4Count , data5Count , data6Count ],
         backgroundColor: ['rgba(25, 82, 105, 0.6'],
          },
      };
    },

    methods: {
    fetchData() {
      axios
        .get('http://127.0.0.1:8000/api/dataList')
        .then(response => {

          this.data1 = [];
          this.data2  = [];
          this.data3  = [];
          this.data4 = [];
          this.data5  = [];
          this.data6 = [];

          response.data.forEach(item => {
            const clusterName = item.Cluster;

            switch (clusterName) {
              case 'Data 1':
                this.data1.push(item);
                break;
              case 'Data 2':
                this.data2.push(item);
                break;
              case 'Data 3':
                this.data3.push(item);
                break;
              case 'Data 4':
                this.data4.push(item);
                break;

              case 'Data 5':
                this.data5.push(item);
                break;  
                
              case 'Data 6':
                this.data6.push(item);
                break; 

              default:
                break;
            }
          }
          );
          
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    },
  },
  mounted() {
    this.fetchData();
  },
  };
  </script>

I am facing the challenge of ensuring that the fetchData method updates the initialized arrays (data1, data2, data3, data4, data5, and data6) directly within the data() section. The goal is to populate these arrays dynamically with API data fetched through the fetchData method so they can be easily used in the charting component.

I would greatly appreciate any advice, examples, or best practices on how to accomplish this task. Since I am new to Vue.js, step-by-step explanations or code snippets would be very helpful. Thank you for your assistance!

Answer №1

It seems like you need to fetch an array of items from your API, organize them into various arrays, and then calculate the length of each array to be added to a Cluster.values property.

To optimize your data() section, consider using an Object or Map instead of multiple arrays:

data() { 
  return {
    namesMap: {'Data 1': [], 'Data 2': []},
    Cluster: {
        labels: ['Data 1', 'Data 2', 'Data 6'],
        values: [],
        backgroundColor: ['rgba(25, 82, 105, 0.6']
    },
  };

}

In the methods section, make the API call, iterate through the items, and add them to the appropriate list in namesMap based on their cluster name:

methods: {
async fetchData () {
    const items = await axios.get('.../api/dataList')
    for (let i = 0; i < items.length; i++) {
        const clusterName = items[i].Cluster
        if (clusterName in Object.keys(this.namesMap)) {
            this.namesMap[clusterName].push(items[i])
        }
    }
    
    Object.keys(this.namesMap).forEach(k => {
        this.Cluster.values.push(this.namesMap[k].length)
    })
    
    // Reset namesMap at the end for the next iteration
    this.namesMap = {'Data 1': [], 'Data 2': []}
}, 

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

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

Updating another component when an input value changes in React

I am currently learning React and I am facing a challenge in updating a component based on an input value. Previously, I had successfully done this using HTML and vanilla JavaScript. Now, I am trying to achieve the same functionality in React but encounter ...

How can I retrieve the line number of a code during runtime in JavaScript?

Is there a way to add a console.log statement that would indicate the line number it is on in JavaScript? For example: console.log ('Line:', [code to get the line]). The output in the console would be Line: [line number], helping me identify wher ...

Ways to identify the active anchor within an li element

Below is the code snippet I am currently working with: <li> <a href="<?php echo base_url()?>home/promos/call" class="promo-call active-call"></a> </li> <li> <a href="<?php echo base_url()?>home/promos/text ...

Using angular.copy function to copy an array with a custom property

Let's use the example below to illustrate an issue: var ar = [4, 2, 3]; ar.$x = 'something'; var br = angular.copy(ar); console.dir(br); After copying ar to br, the $x property is no longer present. This is because when Angular copies an a ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Tips on submitting an Array from a Textarea to mongoDB

I have a question regarding posting an array of serial numbers. When I try to post the serial numbers added in the textarea, they are posted as a single string. Here is my form: <form class="" id="serialsForm" action="/serialsnew" method="post"> &l ...

when the submit button is clicked, verify whether the input field is empty

I have exhausted all my options and nothing seems to work. All I want is for the following functionality to be implemented: When a submit button is clicked -> check if a text field is empty -> if it is, display an error alert and prevent advancing to the ...

Encountering 404 errors on dynamic routes following deployment in Next.JS

In my implementation of a Next JS app, I am fetching data from Sanity to generate dynamic routes as shown below: export const getStaticPaths = async () => { const res = await client.fetch(`*[_type in ["work"] ]`); const data = await re ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

Is there a way to update an angular.js service object without using extend or copy?

I am working with 2 services and need to update a variable in the first service from the second service. Within a controller, I am assigning a scope variable to the getter of the first service. The issue I am facing is that the view connected to the cont ...

How can you make each <li> in an HTML list have a unique color?

Looking for a way to assign different colors to each <li> element in HTML? <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <ul> Here's how you want them displayed: Item 1 should be red Ite ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

jQuery not functioning properly when attempting to add values from two input boxes within multiple input fields

I am facing an issue with a form on my website that contains input fields as shown below. I am trying to add two input boxes to calculate the values of the third input box, but it is only working correctly for the first set and not for the rest. How can ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

Guide to configuring Winston logging with Sequelize correctly

Currently, I am setting up winston with Sequelize and have the code snippet below: const logger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ new winston.transports.File({ filename: path. ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

The issue arises with XMLHttpRequest when there are discrepancies between the event.loaded and event.total values

When using XMLHttpRequest for file upload in the browser, a progress bar is implemented to show the amount of the image that has been uploaded. The following code snippet demonstrates how this is achieved: xhr.upload.addEventListener('progress', ...