Can't render chart, data from api - api

I get data from api. i can show chartdata but it not render a chart.
my code:
<script>
import { Pie, mixins } from 'vue-chartjs'
import axios from 'axios'
export default {
mixins: [mixins.reactiveData],
extends: Pie,
data() {
return {
chartdata: ''
}
},
mounted () {
this.renderChart(this.chartdata, this.options)
},
created() {
axios.get("http://localhost:3000/chart1")
.then(response => {
const responseData = response.data
this.chartdata = {
labels: responseData.map(item => item.lb),
datasets:
[
{
label: 'hrlo',
backgroundColor: ['purple','#b2b2b2'],
data: responseData.map(item => item.dt)
}
]
}
})
.catch( e => {
this.errors.push(e)
})
},
}
</script>
api: [
{
"lb": "Android",
"dt": 80
},
{
"lb": "IOS",
"dt": 20
}
]
i'm sorry because of my bad english.

Can you also include any error messages? I am suspecting that the wrong data structure of "chartdata" is causing an error before even retrieving the data to display, i.e. "chartdata" needs to be
chartdata: {
labels: [],
datasets: []
}

Related

why isnt vue-chartjs receiving data from api?

I don't understand my console log is printing all the data. Do i have to return the data to something for the data to update on the chart? Maybe its something with nuxt? I have tried async mounted and async fetch with the same result. I have tried putting a $ infront of this.$chartData.
<script>
import { Pie } from 'vue-chartjs/legacy'
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js'
import EthplorerService from '../../services/EthplorerService'
import CoinGeckoService from '../../services/CoinGeckoService'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default {
name: 'PieChart',
components: {
Pie,
},
data() {
return {
chartData: {
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#0074D9', '#FF4136', '#2ECC40', '#39CCCC', '#01FF70', '#85144b', '#F012BE', '#3D9970', '#111111', '#AAAAAA'],
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
},
}
},
async created() {
const limit = 10
try {
this.loading = true
const coinData = await CoinGeckoService.getCoinData('chainlink')
const contractAddress = coinData.data.platforms.ethereum
const { data } = await EthplorerService.getTopTokenHolders(contractAddress, limit)
console.log(data.holders.map((x) => x.address))
console.log(data.holders.map((x) => x.share))
this.chartData.labels = data.holders.map((x) => x.address)
this.chartData.datasets.data = data.holders.map((x) => x.share)
this.loading = false
return this.chartData
} catch (e) {
this.loading = false
console.log(e)
}
},
}
</script>
Turns out i was missing the array position [0]. And I was missing the v-if.
this.chartData.datasets[0].data = data.holders.map((x) => x.share)
Followed the examples here and here
<template>
<Pie
v-if="!loading"
:chart-options="chartOptions"
:chart-data="chartData"
:chart-id="chartId"
:dataset-id-key="datasetIdKey"
:plugins="plugins"
:css-classes="cssClasses"
:styles="styles"
:width="width"
:height="height"
/>
</template>
<script>
import { Pie } from 'vue-chartjs/legacy'
import { Chart as ChartJS, Title, Tooltip, Legend, ArcElement, CategoryScale } from 'chart.js'
import EthplorerService from '../../services/EthplorerService'
import CoinGeckoService from '../../services/CoinGeckoService'
ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)
export default {
name: 'PieChart',
components: {
Pie,
},
props: {
chartId: {
type: String,
default: 'pie-chart',
},
datasetIdKey: {
type: String,
default: 'label',
},
width: {
type: Number,
default: 400,
},
height: {
type: Number,
default: 400,
},
cssClasses: {
default: '',
type: String,
},
styles: {
type: Object,
default: () => {},
},
plugins: {
type: Array,
default: () => [],
},
},
data() {
return {
loading: true,
chartData: {
labels: [],
datasets: [
{
data: [],
backgroundColor: ['#0074D9', '#FF4136', '#2ECC40', '#39CCCC', '#01FF70', '#85144b', '#F012BE', '#3D9970', '#111111', '#AAAAAA'],
},
],
},
chartOptions: {
responsive: true,
maintainAspectRatio: false,
},
}
},
async mounted() {
const limit = 10
try {
this.loading = true
const coinData = await CoinGeckoService.getCoinData('chainlink')
const contractAddress = coinData.data.platforms.ethereum
const { data } = await EthplorerService.getTopTokenHolders(contractAddress, limit)
console.log(data.holders.map((x) => x.address.slice(1, 5)))
console.log(data.holders.map((x) => x.share))
this.chartData.labels = data.holders.map((x) => x.address.slice(2, 7))
this.chartData.datasets[0].data = data.holders.map((x) => x.share)
this.loading = false
} catch (e) {
this.loading = false
console.log(e)
}
},
}
</script>

Initialization of variables with Vuex

I made a VueJS 3 project with VueX to store the data.
When I print the variable data.doughnutChart.data in the following code it displays
{ "labels": [ "OK", "WARNING", "ERROR" ], "datasets": [ {
"backgroundColor": [ "#d4efdf", "#fdebd0", "#fadbd8" ], "data": [ 3,
1, 2 ] } ] }
But the graph doesn't use these data [3,1,2], the graph uses the values of the initialization in the index.js of VueX.
Here my code :
<template>
{{data.doughnutChart.data}}
<div style="height:200px;width: 200px; position:center">
<vue3-chart-js
:id="data.doughnutChart.id"
:type="data.doughnutChart.type"
:data="data.doughnutChart.data"
:options="data.doughnutChart.options"
></vue3-chart-js>
</div>
</template>
<script>
import Vue3ChartJs from '#j-t-mcc/vue3-chartjs'
export default {
name: 'App',
components: {
Vue3ChartJs,
},
beforeMount() {
this.$store.dispatch("getData");
},
computed: {
data() {
return {
doughnutChart: {
id: 'doughnut',
type: 'doughnut',
data: {
labels: ['OK', 'WARNING', 'ERROR'],
datasets: [
{
backgroundColor: [
'#d4efdf',
'#fdebd0',
'#fadbd8'
],
data: [this.$store.state.nbOk, this.$store.state.nbWarning, this.$store.state.nbError]
}
]
},
options:
{
plugins: {
legend: {
display: false
},
title: {
display: true,
text: 'Current situation'
}
},
}
}
}
}
}
}
</script>
I read the value in my index.js (VueX) :
import axios from 'axios'
import { createStore } from 'vuex'
export default createStore({
state: {
data: [],
nbError : 0,
nbWarning : 0,
},
actions: {
getData({commit}){
axios.get('http://localhost:8080/data/mock.json')
.then(res => {
commit('SET_DATA', res.data)
})}
},
mutations: {
SET_DATA(state, data){
state.data = data.data;
state.nbWarning = 0;
state.nbError = 0;
for (let i = 0; i < state.data.length; i++) {
if(state.data[i].status == 'WARNING'){
state.nbWarning += 1;
};
if(state.data[i].status == 'ERROR'){
state.nbError += 1;
};
};
}
})
However it works when, in my Vuejs project, I go in an other page and come back but not when I just open the project or refresh the page.
Do you know why ?
data property should be defined as computed in order to receive store changes:
<template>
{{data}}
</template>
<script>
export default {
data() {
return {
}
},
computed:{
data(){
return [this.$store.state.nbWarning, this.$store.state.nbError]
}
},
beforeMount() {
this.$store.dispatch("getData");
}
}
</script>

Apexchats.js axios gives me undefined with Vue

I am trying to get data from server using vue and apexcharts, but even after I called data with axios, it gives me undefined..
What have I missed?
template
<apexchart
ref="chart1"
width="100%"
:options="chartOptions" :series="series">
</apexchart>
data from url
{
"pageviews": 1313,
"new_users": 1014
}
script
export default {
data: function () {
return {
series: [],
chartOptions: {
chart: {
type: 'donut',
},
colors: ['#01cd49', '#007568'],
labels: ['new', 're'],
}
},
created: function () {
this.getByVisitor()
},
methods: {
getByVisitor() {
const url = 'url';
axios
.get(url)
.then(response => {
this.$refs.chart1.updateSeries([{
name: 'Sales',
data: response.data
}])
})
.catch(error => (this.byVisitor = error.data));
console.log(`---------------this.$refs.chart1`, this.$refs.chart1);
},
}
See Updating Vue Chart Data
There's no need to directly call the updateSeries() method on the chart component since it is able to react to changes in series. All you have to do is update your series data property
export default {
data: () => ({
series: [], // 👈 start with an empty array here
byVisitor: null, // 👈 you seem to have missed this one for your error data
chartOptions: {
chart: {
type: 'donut',
},
colors: ['#01cd49', '#007568'],
labels: ['new', 're'],
}
}),
created: function() {
this.getByVisitor()
},
methods: {
async getByVisitor() {
const url = 'url';
try {
const { data } = await axios.get(url)
// now update "series"
this.series = [{
name: "Sales",
data
}]
} catch (error) {
this.byVisitor = error.data
}
},
}
}

Unable to display chart using API call in chartjs in the context of Vuejs

Im trying to display chart using chartjs by calling API, but unable to do so.
Here s my LineChart.vue:
<script>
import {Line, mixins} from 'vue-chartjs' // We specify what type of chart we want from vue-chartjs and the mixins module
const { reactiveProp } = mixins
export default { //We are extending the base chart class as mentioned above
extends: Line,
mixins: [reactiveProp],
data () {
return {
options: { //chart options
lineTension: 0,
maintainAspectRatio: false,
legend: {
display: false
},
scales: {
yAxes: [
{
scaleLabel: {
display: false
},
ticks: {
beginAtZero: true,
// eslint-disable-next-line no-unused-vars
callback (value, index, values) {
return `${value }%`
}
}
}
],
xAxes: [
{
type: 'time',
time: {
unit: 'month'
},
scaleLabel: {
display: true,
labelString: ''
}
}
]
}
}
}
},
mounted () {
// this.chartData is created in the mixin
this.renderChart(this.chartData, this.options)
}
}
</script>
And here is my Home.vue where i have imported the LineChart:
<template>
<div class="chart">
<line-chart :chart-data="datacollection"></line-chart>
</div>
</template>
<script>
import LineChart from './LineChart'
import axios from 'axios'
import DateTime from 'luxon'
export default {
data () {
return {
date: {},
challenge: {},
datacollection: {}
}
},
component: {LineChart},
created() {
this.fillData()
},
mounted () {
this.fillData()
},
methods: {
fillData () {
axios.get('https://my_api_goes_here')
.then(response => {
const results = response.data
const dateresult = results.map(a => a.date)
const challengeresult = results.map(a => a.challenge)
this.date = dateresult
this.challenge = challengeresult
this.datacollection = {
labels: [this.date].map(labels => DateTime.fromMillis(labels * 1000).toFormat('MMM yyyy')),
datasets: [
{
data: [this.challenge],
label: 'Africa',
borderColor: '#7367F0'
}
]
}
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
Dont know why the chart did not appear even though my other resources have been loaded from the API call, when i checked out my console, this is what error im getting:
TypeError: results.map is not a function
Please check out my logic and let me where the error is.

How can I fix my Vue component to properly show my Vue-Chart.js line chart?

I would like to create a line chart using the vue-chartjs library.
What I have created so far produces no error but it also renders nothing but a blank canvas. When I switch to the developer view, I notice that all my data prints out. I'm just not sure why it's not rendering.
Here's my HTML and a snippet of the Vue code:
<div class="app">
<h1>Line Chart</h1>
<line-chart></line-chart>
</div>
<script>
Vue.component('line-chart', {
extends: VueChartJs.Line,
mounted () {
this.renderChart({
labels: this.chartDate,
datasets: [
{
label: 'Data One',
backgroundColor: '#f87979',
data: this.expectedFund
}
]
}, {responsive: true, maintainAspectRatio: false})
}
})
new Vue({
el: '.app',
data: {
message: 'Hello World',
dataSetData: [],
expectedFund: '',
chartDate: '',
crossOver: '',
billing: ''
},
methods: {
getDataSet: function(dataField) {
console.log("get data sets");
console.log(this.dataSetData);
this.expectedFund = this.dataSetData.map(function(chartData) {
//alert("expected");
console.log(chartData);
return chartData.ExpectedFund;
});
this.billing = this.dataSetData.map(function(chartData) {
return chartData.Billing;
});
this.billing = this.dataSetData.map(function(chartData) {
return chartData.Billing;
});
this.chartDate = this.dataSetData.map(function(chartData) {
return chartData.date;
});
this.crossOver = this.dataSetData.map(function(chartData) {
return chartData.crossOver;
});
},
getListData: async function() {
const { data } = await axios.get(
"https://my-json-server.typicode.com/isogunro/jsondb/chartData"
);
return data;
}
},
mounted: async function() {
this.dataSetData = await this.getListData();
console.log("ok", this.dataSetData);
this.getDataSet();
}
})
</script>
If the pasted code is not enough, here's the Pen
After much struggle and bouncing around a bunch of Vue discords, I was able to figure out how to create a multi-line and bar-chart using Vue-Chartjs. It was a struggle worth it because I finally understand the use of props and how they work, which is what I was missing with the vuejs charts. Here's a pen showing the solution.
I am posting the json below because my charts use that data found in "my fake json server/typicode". It might change in the future, so I'm pasting it here.
{"chartData":
[
{
"date":"4/4/2019",
"totalCount":381,
"ExpectedFund":191,
"Funded":290,
"Billing":125,
"crossOver":241,
"AcceptedTotal":515
},
{
"date":"4/11/2019",
"totalCount":233,
"ExpectedFund":12,
"Funded":220,
"Billing":125,
"crossOver":211,
"AcceptedTotal":315
},
{
"date":"4/18/2019",
"totalCount":542,
"ExpectedFund":34,
"Funded":240,
"Billing":125,
"crossOver":125,
"AcceptedTotal":415
},
{
"date":"4/25/2019",
"totalCount":154,
"ExpectedFund":49,
"Funded":210,
"Billing":243,
"crossOver":35,
"AcceptedTotal":115
},
{
"date":"5/2/2019",
"totalCount":300,
"ExpectedFund":55,
"Funded":200,
"Billing":125,
"crossOver":145,
"AcceptedTotal":105
},
{
"date":"5/9/2019",
"totalCount":231,
"ExpectedFund":55,
"Funded":250,
"Billing":125,
"crossOver":355,
"AcceptedTotal":215
},
{
"date":"5/16/2019",
"totalCount":331,
"ExpectedFund":77,
"Funded":270,
"Billing":312,
"crossOver":15,
"AcceptedTotal":615
},
{
"date":"5/23/2019",
"totalCount":498,
"ExpectedFund":232,
"Funded":270,
"Billing":312,
"crossOver":15,
"AcceptedTotal":615
},
{
"date":"5/30/2019",
"totalCount":102,
"ExpectedFund":33,
"Funded":150,
"Billing":25,
"crossOver":155,
"AcceptedTotal":315
},
{
"date":"6/6/2019",
"totalCount":293,
"ExpectedFund":235,
"Funded":170,
"Billing":112,
"crossOver":125,
"AcceptedTotal":315
},
{
"date":"6/13/2019",
"totalCount":198,
"ExpectedFund":432,
"Funded":470,
"Billing":112,
"crossOver":315,
"AcceptedTotal":215
}
]
}