Real-time ChartJS using Livewire
New Javascript Livewire
Demo
This is a pro component. Get Livewiredemos pro access to view / download the component code.
Component Overview
This component demonstrates the integration of Chart.js with Livewire, with a sprinkle of some Livewire magic that lets us implement live updates of the Chart.js Component as shown above.Component Class
<?php
namespace App\Http\Livewire;
use Carbon\Carbon;
use Livewire\Component;
use Carbon\CarbonPeriod;
class ChartWithLiveUpdates extends Component
{
public $timestamps = [];
public $usersCount = [];
public function mount()
{
// Generate a time range of 5 items with an interval of 2 seconds
$carbonPeriod = CarbonPeriod::create('now', '2 seconds', 5);
// and format each item as H:i:s and store it in the timestamps array
foreach ($carbonPeriod as $item) {
$this->timestamps[] = $item->format('H:i:s');
}
// Add random users count to each timestamp
foreach ($this->timestamps as $timestamp) {
$this->usersCount[$timestamp] = random_int(0, 100);
}
}
public function render()
{
return view('livewire.chart-with-live-updates');
}
public function updateChart()
{
// on each update, add a new timestamp to the time range
array_push($this->timestamps, Carbon::createFromFormat('H:i:s', last($this->timestamps))->addSeconds(2)->format('H:i:s'));
// and emit an event to update the chart along with the generated label and value
$label = last($this->timestamps);
$value = random_int(0, 100);
$this->emit('updateChart', $label, $value);
}
}
Component View File
<div class="tw-mt-5 tw-bg-gray-100 tw-rounded tw-p-3 tw-border tw-border-gray-200" wire:poll.2s="updateChart">
<div class="tw-flex tw-justify-between">
<div class="tw-mb-3 tw-ml-1 dark:tw-text-purple-800 tw-font-semibold tw-text-lg">Chart with Live Updates</div>
</div>
{{-- wire:ignore will ignore updating this dom when re-rendering the component --}}
<div id="chartWrapper" style="height:400px" wire:ignore>
<canvas id="myChart"></canvas>
</div>
</div>
@push('scripts')
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script type="text/javascript">
$(function() {
/** Chart.js code starts */
document.querySelector("#chartWrapper").innerHTML = '<canvas id="myChart"></canvas>';
const ctx = document.getElementById('myChart');
let userChart = new Chart(ctx, {
type: 'line',
data: {
labels: Object.values(@this.timestamps),
datasets: [{
label: '# of Users',
data: Object.values(@this.usersCount),
borderColor: 'rgb(79, 70, 229)',
fill: false,
tension: 0.1
}]
},
options: {
maintainAspectRatio: false,
},
});
// Listen to the "updateChart" event and push the received label/value to the chart
// and finally update the chart
Livewire.on('updateChart', (label, value) => {
userChart.data.labels.push(label);
userChart.data.datasets.forEach((dataset) => {
dataset.data.push(value);
});
userChart.update();
});
});
</script>
@endpush
Usage
@livewire('chart-with-live-updates')
Documentation
In this component, we are generating some random data to mimic the Live Update feature, and you'll find comments that instruct you on what the code does.
And hence, the concepts demonstrated in this component can be used to build a component that updates at a certain interval or update the Component whenever certain data is added/updated (by firing Livewire events and performing a Component Refresh whenever that event is fired)