Summer Sale! All accounts are 50% off this week.

NicolasJ's avatar

Livewire : call a method of a component after some seconds

Hi all,

still not familar with alpinejs (because I think I need to use it), I start to create a Livewire component with Laravel that is displayed on success action (saved model, etc ...).

When this component is displayed it could be closed with a button, but I would also like to close it automatically after 2 or 3 seconds. I really do not know how to achieve it.

I tried :

x-init="clearTimeout(timeout); timeout = setTimeout(() => { closeComponent }, 2000);"

where closeComponent is a method of the component that is also called on the button :

<button wire:click="closeComponent">Close</button>

help would be welcome :)

0 likes
3 replies
NicolasJ's avatar

Ok, thus the answser is :

1 : to call component method in JS there $wire

2 : need to instanciate x-data

Then, the code comes :

x-data="{}"
x-init="setTimeout(() => { $wire.closeComponent() }, 2000);"

Any suggestions or optimization ?

3 likes
Snapey's avatar

Do you need to tell the component to hide? You could close it with alpine?

NicolasJ's avatar

Hi Snapey, thanks for reply. You're right, but doing it only with alpine will only hide the component and I want to remove it from the DOM.

Please or to participate in this conversation.