I would like to toggle a boolean after a couple of seconds. I originally thought I could set the boolean to be true (showing the toast) and then sleep(2)
and then set the boolean to false again. But all that occurs is (apparently) the sleep is ignored and the boolean is toggled true then immediately false, so you don't even see it appear.
Could anyone shed some light on how / why this occurs and how to overcome it without the use of JavaScript toast alternatives?
public function store()
{
$this->validate();
$this->fileref->save();
$this->show_toast = true; # Toast show
sleep(2); # Wait...
$this->show_toast = false; # Toast hide
}
Here is my solution, per the opening question, not resorting to a Javascript toast library, such as Notyf
or Toastr
. It was not my intention to avoid the use of Javascript altogether.
With that said, by dispatching a browser event (server-side) and then adding a listener to my Component (server-side), I am able to still use mostly the server-side & a simple @if
-wrapped notification (html) to render my toast notification, time it, then remove it.
public function store()
{
$this->validate();
$this->fileref->save();
$this->show_toast = true; # Toast show
$this->dispatchBrowserEvent('fileStored');
}
Then, back on my Livewire Component:
protected $listeners = ['eatToast' => 'hideToast'];
Finally, the only Javascript part:
document.addEventListener('fileStored', function () {
setTimeout(() => {
Livewire.emit('eatToast');
}, 5000);
});
Final method (inside of Livewire Component) to hide toast:
public function hideToast() {
$this->show_toast = false;
}