Supercharge your Laravel Livewire components with wire:loading
Keeping users informed about the status of their actions is essential for a smooth and engaging user experience. Laravel Livewire v3 introduces the wire:loading
directive, which allows you to show loading indicators while actions are being processed. This feature is particularly useful for displaying spinners, messages, or any other indicators during data loading or form submissions.
Understanding wire:loading
The wire:loading
directive automatically shows or hides elements based on the loading state of your Livewire component. This helps you provide instant feedback to users, making your application feel more responsive and interactive.
Basic Usage
Here’s a basic example to illustrate how wire:loading
works:
<button wire:click="save" wire:loading.attr="disabled">
Save
</button>
<span wire:loading>
Saving...
</span>
In this example, the wire:loading
directive disables the save button and shows the "Saving..." message while the save
method is being processed.
Real-Life Example
Consider a scenario where you have a form, and you want to show a loading spinner while the form data is being saved. Here’s how you can implement this using wire:loading
:
use Livewire\Component;
class UserProfile extends Component
{
public $name;
public $email;
public function save()
{
// Simulate a save operation with a delay
sleep(2);
// Save user profile data
// User::update(['name' => $this->name, 'email' => $this->email]);
}
public function render()
{
return view('livewire.user-profile');
}
}
<!-- Blade Template (livewire/user-profile.blade.php) -->
<form wire:submit.prevent="save">
<input type="text" wire:model="name" placeholder="Name">
<input type="email" wire:model="email" placeholder="Email">
<button type="submit" wire:loading.attr="disabled">
Save
</button>
<div wire:loading>
<span>Saving...</span>
<img src="/images/spinner.gif" alt="Loading">
</div>
</form>
In this example, the form inputs are disabled, and a loading spinner is displayed while the save
method is being executed. This provides a clear visual indication to the user that their data is being processed.
Conclusion
The wire:loading
directive in Laravel Livewire v3 is a powerful tool for enhancing user experience by providing instant feedback during data processing. By leveraging this feature, you can improve the responsiveness and interactivity of your application. Give wire:loading
a try in your next Laravel Livewire project and see how it can make a difference.