SnapShooter Backups Server, Database, Application and Laravel Backups - Get fully protected with SnapShooter

Laravel Livewire Tip - Loader Listening to Events

When using the loading state in Laravel Livewire, you can target specific actions and models. However, there is no way to show targeted loading states on things that happen because of livewire events. which makes working with multiple components on a page that communicate via events a bad experience for the user.

In this post, we share a workaround. Due to the internal implementation of Laravel Livewire, it is impossible to target events for the loader. However, Laravel Livewire can target action and it provides a JavasScript event listener. If we trigger the action when the event happens using JavaScript, it will work.

Let's say I have a listener on the PHP side that triggers an action handleSelection. if I set up a loading target such as wire:target="handleSelection", it never works. On the other hand, if I listen for the event in javascript, it now works:

<script wire:ignore>
        document.addEventListener("DOMContentLoaded", () => {
            window.Livewire.on("selected", (item) => {
                @this.handleSelection(item);
            });
        });
</script>

In the workaround, we listen to the event using JavaScript and manually trigger the action in the front end, so the loader starts to work.