Laravel Livewire 3 unmount hook/lifecycle

65 views Asked by At

I am wondering if there is any mechanism or hook which would fire when a component unmounts. I looked through both v2 and v3 docs and I couldn't find something like that.

Use case: I am looking to integrate Laravel Reverb into my app and I would like a hook to close the ws connection for a certain component with Echo.leave('channel-name').

1

There are 1 answers

2
Adam On

For livewire 3

doing a quick search through the livewire code there is the following function within the ComponentHook.php file

function callDestroy(...$params) {
    if (method_exists($this, 'destroy')) $this->destroy(...$params);
}

this seems to imply if you add a destroy() function to your component class this would handle the "unmount"

it may be the case that you will need to implement some additional Alpine code to really get to the solution that you want.

again in the livewire codebase there is the following documentation:

In certain scenarios, you might need to unregister global Livewire events. For instance, when working with Alpine components and wire:navigate, multiple listeners may be registered as init is called when navigating between pages. To address this, utilize the destroy function, automatically invoked by Alpine. Loop through all your listeners within this function to unregister them and prevent any unwanted accumulation.

Alpine.data('MyComponent', () => ({
    listeners: [],
    init() {
        this.listeners.push(  
            Livewire.on('post-created', (options) => {  
                // Do something...
            })
        );
    },
    destroy() {
        this.listeners.forEach((listener) => {  
            listener();  
        });
    }
});