Vue3 script setup ChartJS not rendering with reactive data

227 Views Asked by At

As most advice, I've read from the forums is to use computed or props when trying to pass a reactive value on Chart data. I have done that but the issue is the chart does not even display.

<script setup>
import { partnerState } from '@/state/partnerState.js';
import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip } from 'chart.js';
import {computed, reactive, ref} from 'vue';
import { Bar } from 'vue-chartjs';
import {storeToRefs} from "pinia";

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale);

const options = reactive({
    responsive: true,
    maintainAspectRatio: false,
    scales: {
        ...
    },
    plugins: {
        ...
    }
});

const state = partnerState();
const stateData = storeToRefs(state); //using storeToRef to convert state to reactive
if (state.partnerAnalysis === null) {
    await state.getPartnerAnalysis();
}
const data = computed(() => ({
    labels: Object.keys(stateData.partnerAnalysis.newPurchases) // this returns an array of labels,
    datasets: [
        {
           ...
        },
        {
           ...
        }
    ]
}));
</script>

<template>
    <Bar id="partner-analysis-chart" :options="options" :data="data" />
</template>

What's the cause of chart not rendering when it has already been set to computed and I am also able to retrieve the data from API ?

Related post I've read: Pinia ChartJs Vue3 & Computed Chartjs Vue3

1

There are 1 best solutions below

0
On

You have to make sure, that the data you want to pass to the chart is available before you render the chart.

https://vue-chartjs.org/guide/#chart-with-api-data