Hello,
I display a chart with Livewire / AlpineJS / ChartJS.
I think it's not a Livewire problem, but it's an AlpineJS problem. As there isn't any AlpineJS category here, I post this in the Livewire category.
In the Livewire component, I retrieve the datas for 2 charts.
class Charts extends Component
{
public $charts = [];
public $activeChart = 0;
public function mount()
{
$this->charts[] = (new ChartService)->categories();
$this->charts[] = (new ChartService)->shops();
}
public function render()
{
$categoriesChartHeight = 50 + Category::count() * 50;
$shopsChartHeight = 50 + Shop::count() * 50;
return view('livewire.charts', compact('categoriesChartHeight', 'shopsChartHeight'));
}
}
In the view, I display the first chart.
<section
wire:ignore
class="w-full space-y-4"
x-data="{
activeChart: $wire.entangle('activeChart'),
charts: @js($charts),
chart: null,
toggle(chartToActivate) {
this.activeChart = chartToActivate;
this.chart.data = this.charts[this.activeChart].data;
this.chart.update();
},
}"
x-init="
chart = new Chart($refs.chart, charts[activeChart]);
"
>
<div class="flex justify-center items-center gap-8">
<template x-for="index in [...Array(charts.length).keys()]" :key="'chart-'+index">
<span x-on:click="toggle(index)" class="cursor-pointer">
<i x-show="index == activeChart" class="fa-solid fa-circle fa-lg"></i>
<i x-show="index != activeChart" class="fa-regular fa-circle fa-lg"></i>
</span>
</template>
</div>
<article
class="relative w-full bg-white rounded-lg px-3 py-2"
style="height: {{ $categoriesChartHeight.'px' }}"
>
<canvas x-ref="chart"></canvas>
</article>
</section>
The problem is when I click on the span to toggle to the second chart.
The chart isn't updated and I get this error.
Alpine Expression Error: Maximum call stack size exceeded
If I remove the this.chart.update(); line, I don't get the error any more."
For the moment the only solution I have found is to destroy the chart chart.destroy() and to create a new one with the new data. But doing this, I get a new error if I switch to the other chart before the animation is finished for the first displayed chart.
Uncaught TypeError: Cannot read properties of null (reading 'save')
Can you help me please ?
Thanks a lot.
V