0
votes

I am using Laravel 8 with Livewire and have a component that is supposed to dynamically display many charts. So in this main component I create any number of sub-components of type productiv-component in a foreach loop:

<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 py-3 px-3">
@foreach($customer as $k)
    @livewire('productiv-component', ['planedTimeData' => $planedTimeDataArray[$k->id],
    'employeeTimeData' => $employeeTimeData[$k->id]], key('cust-'.$k->id))
@endforeach

productiv-component itself contains code for a Google chart. I pass the data for this from the main component to the sub-component.

 <div class="px-4 py-0 col-span-3"> 
//setRandom() generates a random number and stores it in the variable random, 
//so that the chart ID is unique and the charts are displayed again when rerendering
{{\App\Http\Livewire\KpiProductivComponent::setRandom()}}
<div id="chart{{$random}}" style="height: 275px"></div>
<script>
    var chartData = <?php echo ($chart); ?>;
    google.charts.setOnLoadCallback(lineChart);
    function lineChart() {
        var data = google.visualization.arrayToDataTable(chartData);
        var options = {
            curveType: 'line',
            legend: {
                position: 'bottom'
            },
            backgroundColor: 'transparent',
            lineWidth: 3,
            chartArea: {  width: "90%", height: "60%" }
        };
        var chart = new google.visualization.LineChart(document.getElementById('chart{{$random}}'));
        chart.draw(data, options);
    }
</script>

The problem now is that the charts all render the same data, even though it is definitely not identical. Also, when I output the chartData variable in the code of the Google Chart, the different data sets arrive correctly for each chart, they just don't render correctly. The mapping of the last rendered chart is applied to all previous ones as well. If I render only one chart, it is rendered correctly, so the error seems to occur because I use the same component multiple times with new data.

all charts render the same data although they are definitely different

Here is also an image with the browser output, where you can see that both charts get different data sets and are also assigned to a different id and even though the same chart is rendered

Rendered charts with code within the browser

Does anyone have any ideas as to what this could be? Thanks a lot.

1
are you having some typo in directive??? some ']' missing - Prospero
you are absolutely right, but unfortunately the error happened when transferring here and in my code ] is not missing. Thanks for the quick response - ed_dev

1 Answers

0
votes

I found a solution. It seems to be a problem with the multiple use of the var chartData in the tag of the google chart. I put the passed data directly in the linechart function and it works fine now.

<script>
    function lineChart() {
        var data = google.visualization.arrayToDataTable(<?php echo ($chart); ?>);