Search code examples
vue.jsweb-applicationsapexcharts

Apexchart does not update dynamically using axios


The updateSeries function does not seem to work. I can't find out why it doesn't though. The uChart() function does indeed get called. I have the following code:

<template>
<div>
    <Menu></Menu>
    <h1> Our Home Website! </h1>

    <apexchart ref="chart1" width="500" type="line" :options="options" :series="series"></apexchart>
</div>

import Menu from './Menu' import axios from 'axios'

export default {
    name: 'Home',
    components: {
        'Menu': Menu
    },
    data: function () {
        return {
            options: {
                chart: {
                    height: 350,
                    type: 'bar',
                    id: 'chart'
                },
                dataLabels: {
                    enabled: false
                },
                series: [],
                title: {
                    text: 'Ajax Example',
                },
                noData: {
                    text: 'Loading...'
                }
            }
        }
    },
    mounted: function () {
        this.uChart()
    },
    methods: {
        uChart: function() {
            axios
                .get('http://my-json-server.typicode.com/apexcharts/apexcharts.js/yearly')
                .then(function (response) {
                    this.$refs.chart1.updateSeries([{
                        name: 'Sales',
                        data: response.data
                    }])
                });
            console.log(this.$refs.chart1);
        }
    }

The reference to the chart works as well as the link for the JSON data. But the chart remains on the "loading" state.: This is how it actually looks like on the website and the errors that I get


Solution

  • As Estus Flask mentioned in his comment. The answer to this question is to use the arrow syntax for the "then" argument because it is a callback. Therefore the correct function looks like this:

        methods: {
        uChart: function() {
            axios
                .get('http://my-json-server.typicode.com/apexcharts/apexcharts.js/yearly')
                .then(response => {
                    this.$refs.chart1.updateSeries([{
                        name: 'Sales',
                        data: response.data
                    }])
                });
            console.log(this.$refs.chart1);
        }
    }
    

    For further details around this topic check the answer to this question: How to access the correct this inside a callback?