0

I'm new to Vuejs, and I want to make my code effective by fetching the data from API rather than giving the data directly.

Here is my code:

<template>
  <canvas id="myChart" width="550" height="300"></canvas>
</template>

<script>

export default {
  name: 'Chart',
  data: () => ({
    arrdate: [
      1600934100.0,
      1602009600.0,
      1602747060.0,
      1603050158.390939,
      1603305573.992575
    ],
    arrchallenge: [
      9.0,
      9.5,
      2.5,
      11.52,
      12.4
    ]
  }),
  mounted () {

    // eslint-disable-next-line no-unused-vars
    const data = this.arrdate.map((arrdate, index) => ({
      x: new Date(arrdate * 1000),
      y: this.arrchallenge[index]
    }))

    const ctx = document.getElementById('myChart').getContext('2d')
    // eslint-disable-next-line no-undef,no-unused-vars
    const myChart = new Chart(ctx, {
      type: 'line',
      data: {
        datasets: [
          {
            data,
            label: 'Performance',
            borderColor: '#7367F0'
          }
        ]
      },
      options: {
        scales: {
          xAxes: [
            {
              type: 'time',
              time: {
                unit: 'month',
                displayFormats: {
                  month: 'MMM YYYY'
                }
              }
            }
          ],
          yAxes: [
            {
              ticks: {
                // eslint-disable-next-line no-unused-vars
                callback (value, index, values) {
                  return `${value  }%`
                }
              }
            }
          ]
        }
      }
    })
  }
}
</script>

As you can see, the "date" and "challenge" contains data which is fed directly, but I want to fetch data from API.

What my API returns:

 {  
     "date": [
                 1600934100.0,
                 1602009600.0,
                 1602747060.0,
                 1603050158.390939,
                 1603305573.992575
             ],

    "challenge": [
                       9.1
                       9.5
                      -2.8
                       18.52
                       15.4
            
                 ]
  }

So as you can see my API, I want the "date's" data to be in arrdate and "challenge's" data to be in arrchallenge by using API.

Someone please help me with this, and if someone knows the answer please send me the changes by adding it to my code itself because I'm new to vuejs wrapping the contents would be difficult for me.

2
  • Call your API using an HTTP client like Axios or the native fetch method then load the response into your data properties and draw your chart Commented Dec 16, 2020 at 3:47
  • How can i do that in my code, can you please show me, and where i should place that in my code and i want to call date and challenges from my API. Commented Dec 16, 2020 at 4:18

2 Answers 2

1

first add axios to your project and read the link below from vue documentation:

using axios with vue

after that you have two options:

Call API on page load

with this option your API calls as soon as your vue app loads so in your created hook do the API call like this:

created() {
axios.get('yourAPIUrl').then((response) => {
  // reassign date and challenge with the response from the API call here for example:
  this.date = response.data.date;
  this.challenge = response.data.challenge
});
}

basically what it does is that you call the API when your vue is created and in the then part you use the response to updata the variables defined in your data object.

Call API on button click

with this method you have a button on your page like this:

<button @click="callAPI">get data from server</button>

when you click the button it calls the callAPI method and in your methods you have the same code as before, like this:

methods: {
  callAPI() {
    // same code as in the created example
  }
}

you can also use async ... await syntax for API call if you want to.

also you can read this article on how to install and use axios in your project:

use axios API with vue CLI

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your response, I will use " Call API on page load ", now can you please tell me where i should place it in my code which i have given above, and after that what variable i should use in "arrdate and arrchallenge" in order to use the data of " date & challenge " which is coming from API. Please do help me as I'm new to vuejs
in your vue object define created() just like you defined mounted() in your code (like put it above the mounted(), it doesn't really matter), then implement the API call like the example in my answer. after that check your network tab to see where is your desired data in the api response. most probably you can access it in then like response.data.'variableName'. and then use that to set the appropriate data of your vue object, just like the example in the answer.
Yes i loaded my API as you said, now i have only one question is that what variable should i use in "arrdate & arrchallenge" which is in my code. I tried using this.date in arrdate and this.challenge in arrchallenge. But nothing was displayed in my chart. So can you please send me by modifying or changing my code so that i can understand it better.
Hello Hamid, can you please send me how to do it, I dint find any solution to it, and wrapping up the contents have become a task for me as I'm new to vuejs.
Hi there, do you have vue dev tools installed on your browser? unfortunately I'm not familiar with the chart your using and can't help you debug that part. but if you have vue dev tool, you can check that to see If you are updating your data object correctly with the API response. if the data is updated correctly then the problem is in implementing the chart. if not you can edit your question to provide info about what you've tried and what you've achieved so far so you can get proper help. or even better provide a link to a code pen so it can be debugged better. hope you can debug the problem
1

I created this API for you to use to test out the solutions provided by anyone:

https://wirespec.dev/Wirespec/projects/apis/Stackoverflow/apis/fetchChartDataForVueJs

And here is the response:

https://api.wirespec.dev/wirespec/stackoverflow/fetchchartdataforvuejs

You can also create your own API on Wirespec and use it to generate more data (sequential or random) if you need more diverse testing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.