Enhance your Livewire components with wire:poll.visible in Laravel Livewire v3

Real-time updates are crucial for applications that require continuously refreshed data, such as dashboards or live feeds. Laravel Livewire v3 introduces the wire:poll.visible directive, which allows you to automatically refresh data only when the component is visible. This helps reduce unnecessary server requests and ensures your application remains efficient.

Understanding wire:poll.visible

The wire:poll.visible directive triggers a method in your Livewire component at a specified interval, but only when the component is visible in the viewport. This is particularly useful for optimizing performance by avoiding redundant updates when the user is not viewing the component.

Basic Usage

Here’s a basic example to illustrate how wire:poll.visible works:

<div wire:poll.visible.10s="refreshData">
    <!-- Your component content -->
</div>

In this example, the refreshData method in your Livewire component is called every 10 seconds, but only when the div is visible on the screen.

Real-Life Example

Consider a scenario where you have a dashboard that displays live data, such as stock prices or system metrics. You want to ensure that the data is only refreshed when the user is actively viewing the dashboard. Here’s how you can implement this using wire:poll.visible:

use Livewire\Component;

class Dashboard extends Component
{
    public $data;

    public function mount()
    {
        $this->refreshData();
    }

    public function refreshData()
    {
        // Fetch the latest data
        $this->data = DataFetcher::getLatestData();
    }

    public function render()
    {
        return view('livewire.dashboard');
    }
}
<!-- Blade Template (livewire/dashboard.blade.php) -->
<div wire:poll.visible.10s="refreshData">
    <h1>Live Data</h1>
    <ul>
        @foreach($data as $item)
            <li>{{ $item->name }}: {{ $item->value }}</li>
        @endforeach
    </ul>
</div>

In this example, the refreshData method fetches the latest data every 10 seconds, but only when the dashboard is visible. This ensures that the data is kept up-to-date without making unnecessary server requests when the user is not viewing the dashboard.

Conclusion

The wire:poll.visible directive in Laravel Livewire v3 is a powerful tool for optimizing real-time updates in your applications. By leveraging this feature, you can ensure that data is refreshed efficiently, reducing server load and improving performance. Give wire:poll.visible a try in your next Laravel Livewire project and see how it can enhance your application's real-time capabilities.

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe