And the last mini-project will be to automatically refresh the component using polling Livewire feature. In this example, we will show random dog pictures from the API, and after a couple of seconds, it will get changed.
So first, we need a Livewire component.
php artisan make:livewire Autorefresh
We must get the image URL from the API in the component's class.
app/Livewire/Autorefresh.php:
use Illuminate\Contracts\View\View; class Autorefresh extends Component{ public function render(): View { $cat = file_get_contents('https://random.dog/woof.json'); $image = json_decode($cat, true)['url']; return view('livewire.autorefresh', compact('image')); }}
And now, we can show the image.
resources/views/livewire/autorefresh.blade.php:
<div wire:poll.3s> <img src="{{ $image }}" width="500"></div>
The main code part here is the wire:poll
directive. It tells Livewire to do an update. By default, it makes servers requests every 2.5s, but here we tell it to make it every 3s instead.
You can also specify an action to fire on the polling interval by passing a method name to wire:poll
:
<div wire:poll="refresh"> // ...</div>
Now, the refresh
method on the component will be called every 2.5 seconds.
You can read more about polling in the official documentation.