Assign the values from the axios response to variables within the exported const

Currently, I am incorporating axios into my vue.js application to perform an HTTP POST request and retrieve some variables for a vue-echart. However, I have encountered a bit of a roadblock in determining the most effective approach.

The snippet below is extracted from my dashboard.vue file:

<script>

import { echartBar, echartPie } from "@/data/echarts";

import { echart1, echart2, echart3 } from "@/data/dashboard1";

export default {
  metaInfo: {
    title: "Dashboard v1"
  },
  mounted () {
    axios
      .post('https://testsite.com', 'Request data here')
      .then(response => {
        this.dataNeeded = response.data
        console.log(info)
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
  },
  data() {
    return {
      echartBar,
      echartPie,
      echart1,
      echart2,
      echart3,
    };
  }
};
</script>
<style>
.echarts {
  width: 100%;
  height: 100%;
}
</style>

Below is the constant exported from echarts.js:

var dark_heading = "#c2c6dc";
var chartLabels = ['Test1', 'Test2']

import { zoomBarData } from '@/data/echartSeries'

// start::echartBar
export const echartBar = {
        legend: {
            borderRadius: 0,
            orient: 'horizontal',
            x: 'right',
            data: chartLabels
        },
        grid: {
            left: '8px',
            right: '8px',
            bottom: '0',
            containLabel: true
        },
        tooltip: {
            show: true,
            
            backgroundColor: 'rgba(0, 0, 0, .8)'
        },
        
        xAxis: [{
            type: 'category',
          
            data: dataNeeded.months,
            axisTick: {
                alignWithLabel: true,
               
            },
            splitLine: {
                show: false
            },
            axisLabel: {
                color: dark_heading,
            },
            axisLine: {
                show:true,
                color: dark_heading,
                
                lineStyle: {
                color: dark_heading,
                
                }
            }
        }],
        yAxis: [{
          type: 'value',
          
        
          axisLabel: {
            color: dark_heading, 
            formatter: '${value}'
        },
        axisLine: {
            show:false,
            color: dark_heading,
            
            lineStyle: {
            color: dark_heading,
            
            }
        },
          min: 0,
          max: 100000,
          interval: 25000,
      
          splitLine: {
              show: true,
              interval: 'auto'
          }
      }],
 

  series: [{
          name: chartLabels[0],
          data: dataNeeded.amounts,
          label: { show: false, color: '#0168c1' },
          type: 'bar',
          barGap: 0,
          color: '#bcbbdd',
          smooth: true,
          itemStyle: {
              emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowOffsetY: -2,
                  shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
          }
      },
      {
          name: chartLabels[1],
          data: dataNeeded.amounts2,
          label: { show: false, color: '#639' },
          type: 'bar',
          color: '#7569b3',
          smooth: true,
          itemStyle: {
              emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowOffsetY: -2,
                  shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
          }
      }

  ]
}

If my aim is to substitute the data retrieved from the axios JSON response for the hardcoded data in echarts.js (as an exported constant), what would be the optimal solution?

Answer №1

The const is essentially returning a plain object. When Axios receives the object data, you can easily access or assign its values to other objects.

In your scenario, you can set a value for the echartBar object within the context of your component like this:

this.echartBar.xAxis[0].data = response.data.months

This assumes that there is a months property in your response data.

This process can become tedious especially when dealing with numerous properties on the echartBar object as seen here. It becomes necessary to verify arrays within arrays etc. Utilizing libraries such as lodash might be beneficial in these situations, such as its set function: https://lodash.com/docs/4.17.15#set

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

What is the best way to convert a series of sentences into JSON format?

I'm struggling with breaking down sentences. Here is a sample of the data: Head to the dining room. Open the cabinet and grab the bottle of whisky. Move to the kitchen. Open the fridge to get some lemonade for Jason. I am looking to format the outc ...

Utilize clipboard functionality in automated tests while using Selenium WebDriver in conjunction with JavaScript

How can I allow clipboard permission popups in automated tests using Selenium web driver, Javascript, and grunt? https://i.stack.imgur.com/rvIag.png The --enable-clipboard and --enable-clipboard-features arguments in the code below do not seem to have an ...

What is the best way to increase a count in MongoDB?

I need to update the quantity count in my database every time I click a specific button. Here is the Angular directive I am using: var count = 0 $scope.postNote = function () { var deferred = $q.defer() var token = $scope.userInfo.$$state.valu ...

Loading a specific number of rows in Datatables upon page loading: How to do it?

Recently, I came across a code snippet that uses AJAX to retrieve data from a specific URL and then displays the information in a table. However, I have a requirement to only load and display the first 10 rows of data during the initial page load process. ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Exploring the functionality of inline easing when using the ScrollTo plug-in

Attempting to utilize the ScrollTo plug-in with an easing effect. I prefer not to include the easing plug-in file, as I will only use it once and for a single easing effect. The specific 'easeOutBack' function I aim to implement is: easeOutBac ...

What is the best method to position a modal in the exact center of the screen?

Is there a way to position the modal at the center of the screen? I have tried implementing this HTML and JavaScript code. Interestingly, it works fine in Chrome console but fails when I try to refresh the page. $('.modal').css('top', ...

Electronic circuit embedded within a material-textured text field offering multiline functionality

While experimenting with TagsInput, I came across this helpful snippet on codesandbox that you can check out here. The challenge I encountered is when there are numerous chips, they extend beyond the boundaries of the text field. My goal is to implement ...

Leveraging JavaScript to trigger onClick() functions for multiple buttons throughout a webpage

        While searching for solutions, I came across several articles with similar topics, but unfortunately, none of the proposed solutions worked. Please forgive me if it was due to my own error. Background I am assisting a client who is transition ...

What is the process of importing the csv-writer module?

Can we use the import statement instead of const createCSVWriter = require('csv-writer').createObjectCsvWriter; Is there a way to achieve this using import ...

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

Simplified method of connecting dynamic components without needing to remember functions in jQuery

I have a page where users can freely move, resize, and modify content. The basic setup is as follows: $('.element').on().resizable().draggable(); When this code is called on page load, it allows elements to be resizable and draggable. The issu ...

Having trouble with querySelector or getElementById not functioning properly?

Currently, I am in the midst of developing an experimental web application that features a quiz component. For this project, I have implemented a Python file to handle the questions and quiz functionalities. However, I have encountered an issue with the Ja ...

Dynatree fails to consider the select feature while utilizing ajax requests

Currently, I am utilizing the dynatree plugin to exhibit a checkbox tree in multi-select mode (mode 3). Upon initializing the tree using ajax (without lazy loading), it appears that certain nodes that were initially loaded as selected are forgotten. When ...

Is there a way to capture the stdout and stderr output from a WebAssembly module that has been generated using Emscripten in JavaScript?

In my C++ code snippet below: #include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } I compile the code using: emcc -s ENVIRONMENT=shell -s WASM=1 -s MODULARIZE=1 main.cpp -o main.js This c ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Retrieving JSON Data from an API with JavaScript/jQuery

Having some trouble with JSON parsing using jQuery and JavaScript. I'm trying to fetch weather information from the open weather simplest API, but for some reason it's not working. When I hardcode the JSON data into a file or my script, everythin ...

employing a flexible array of gulp operations in run-sequence

I have a situation where I need to create gulp tasks with dynamic names and ensure that they run in sequence, not parallel. I have stored the task names in an array, but when I try to use run-sequence, I encounter an error. I suspect the issue lies in how ...

Displaying the quantity of directories within a specific location

Can anyone help me troubleshoot my code? I'm trying to have a message displayed in the console when the bot is activated, showing the number of servers it is currently in. const serversFolders = readdirSync(dirServers) const serversCount = parseInt(s ...

JavaScript: Adding up whole numbers--- Reference Error: Undefined

I'm having trouble with my code because it's saying that "t1" is not defined, even though it's the name of my text box. I tried making the variable global by declaring it outside the function, but it didn't solve the issue. Interestingl ...