Occasionally, you'll need to manually re-render a Livewire component to update its contents. Let's discuss a few ways to do this.
At the heart of everything is the built-in $refresh
action. Here's how it works in a Livewire component.
class SomeComponent extends Component
{
protected $listeners = [
'some-event' => '$refresh'
];
public function someAction()
{
$this->dispatch('some-event');
}
}
In this component, any time a some-event
event is dispatched, the $refresh
action will be invoked, which will refresh your Livewire component.
Since we can globally dispatch events, you can refresh any component in response to an action in another component. I covered this in the Livewire Trello Clone course here on Codecourse.
If you need to refresh the component from within itself and don't need to rely on events, there's a much easier way. In the template for your Livewire component, just invoke $refresh
directly.
<button wire:click="$refresh">Refresh this component</button>
The click event above triggers a call to the $refresh
action and will re-render the Livewire component.
Oh, we can do it from Alpine too! Using Alpine to refresh a Livewire component is helpful when you need to refresh your component inside a JavaScript condition or event.
Here's an example of refreshing a Livewire component every 5 seconds (not recommended for most scenarios, but could be useful).
<div
x-init="
setInterval(() => {
$wire.$refresh()
}, 5000)
"
>
This will get refreshed every 5 seconds
</div>
Of course, you can also directly link this to a button action using Alpine.
<button x-on:click="$wire.$refresh()">
Refresh this component using an Alpine click event!
</button>
The $commit
helper does the same thing as $refresh
(they're entirely identical). So, if you prefer this, you can also invoke this to re-render a Livewire component.
<button wire:click="$commit">
Refresh this component using $commit!
</button>
That's a wrap — you're spoiled for choice when it comes to methods for re-rendering Livewire components.