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

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...

Using the Context API dispatch (consumer) within the _app.js class component in Next.js

How can I access the dispatch Context API methods in the _app.js file? The issue I am facing is that I am using React hooks along with Context API, and as _app.js is a Class component, I cannot directly use hooks within it. Below is my current code snipp ...

Establish dynamic dropdown options in Vue.js based on specific conditions

I need to populate a dropdown menu with a collection of objects. The default binding for the dropdown should be based on a specific condition. <tr v-for="item in binSalesList">\ <template v-if="item.IsRemovedBin != isRemoved">\ ...

Retrieving AJAX data in a Node.js environment

In my HTML application, I am utilizing AJAX to showcase the output on the same page after the submit button is clicked. Before submitting, I am able to retrieve the values passed in the HTML form using: app.use(express.bodyParser()); var reqBody = r ...

tips for converting a single observable item into an observable list

Within my Angular project, there exists an observable object with the following structure: export interface FavoritesResponse { wallet: boolean; deposit: boolean; withdraw: boolean; transfer: boolean; exchange: boolean; ticket: boolean; accou ...

Increase visibility, decrease visibility by utilizing ng-hide/ng-show and functions

As I implement the show more/show less feature, I am uncertain if achieving a smooth effect is feasible. However, I believe it's worth reaching out to this community for some creative ideas on how to make it possible. I have a list of dynamic links w ...

What is the best way to find the product of each object in an array by the corresponding values in another array?

Searching for a solution to an issue I encountered while working on an assignment. The problem can be illustrated as follows: var arrOfObj = [{a:10 },{a:20},{a:30}, ......] var arrToMultiply = [2,4,6, .....] The expected result const result = [{a:10,resul ...

Adjust the width of a textarea dynamically as you type by detecting keyup events

Two text areas have the same text formatting. Their IDs are textareaA and textareaB. I've successfully added functionality to resize textareaA on keyup. How can I make textareaB resize its WIDTH while the user is typing in textareaA? Here's wha ...

Are you utilizing content loaded through jquery load in your work?

I have successfully utilized jQuery's .load() function to retrieve the contents of a table from another webpage and insert it into the current page, which is functioning properly. However, when I try to run scripts afterwards that manipulate the newly ...

Developing an interactive graph with Django and harnessing the power of chart.js

I’m currently navigating the world of Django as a newcomer. My current project involves conducting sentiment analysis on real-time user tweets using the Twitter API. I've successfully analyzed and displayed the sentiments extracted from these tweets ...

Problem with Node JS controller when using async/await

While working on my Node API controller, I encountered an issue with my 'error-handler' middleware related to using an asynchronous function. TypeError: fn is not a function at eval (webpack:///./app/middleware/errorHandler.js?:16:21) T ...

Validating fields using JavaScript and HTML

I'm having an issue with the code below because it only allows me to log in with the user and password from the last position of the arrays. I want it to let me login with each user and their corresponding password, for example, user at position 1 wit ...

What can be done to ensure smooth functionality of my nested navigation menu on mobile devices?

I'm utilizing the incredible features of Base Web for my website. One of the components I am using is a menu with a child menu, based on this example. The menu works perfectly fine on desktop - when I hover over an option, the child menu appears. Howe ...

Creating a table in Javascript using an array of objects

I need a larger version of this data structure. [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zo ...

Triggering the JavaScript KeyUp() event for input values consisting of multiple digits

I'm currently working on a JavaScript project that involves displaying numbers from 1 to N based on user input. I am utilizing the keyup() event for this functionality. When the input field is cleared, it correctly displays nothing thanks to the empty ...

The attribute "value" for Material-UI autocomplete cannot be used in conjunction with the "getOptionLabel" attribute

<Autocomplete id="license-select" options={licReqList} value = {licReqList[0] ? licReqList[0].licReqStr : null} getOptionLabel={(option) => option.licReqStr} onChange={ha ...

Implementing transparency to clip-path using HTML and CSS

How can I apply opacity to the clip-path/clip area, similar to the image shown below? Please find my code snippet for reference: .item--clip .demo { width: 200px; height: 250px; } .item--clip .has-mask { position: absolute; clip: rect(10px, 19 ...

Determine the number of network requests being made on a webpage

In my quest to develop a universal method using selenium, I am seeking a way to ensure that all background network activities, including Ajax, Angular, and API calls, have completed. While I am aware of the option to determine the number of active Ajax cal ...

In my experience, I have encountered issues with certain routes not functioning properly within Express

I am currently working on developing a tic-tac-toe game and looking to store user data in a database. However, I am facing an issue with the router I intended to use for this purpose as it is returning an 'Internal server error message (500)'. B ...