Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event listener not picking up Laravel Livewire emit from mount() method (but working when firing from blade)

I have nested Livewire components, where the "child" fires an event to the "parent".
The issue is that it does not reach the listener when firing from the child's (mount) method.
Maybe the listener is not yet available when firing the event from child?
It does work when firing from the child's blade, using wire:click="$emit(...)" or global JavaScript.

Analogy for my setup: the first method gets the Posts and the second method gets+manages the Comments, and I want to let first know how many comments are on the page so it can update the counter. This can be done as part of the mount() where I get the Comments.

How do I fire an event from the child's mount() method, and/or are other ways more suitable?

First.php

protected $listeners = ['testEmit'];

public function testEmit() {
   Log::info("testEmit listener"); // only received when firing from blade
}

first.blade.php

@livewire('second')

Second.php

    public function buttonClick()
    {
        // works
        $this->emit('testEmit', 'Second (method buttonClick)');
    }

    public function mount()
    {
        // not working (is sent but not received)
        $this->emit('testEmit', 'Second (method mount)');
    }

    public function render()
    {
        // does not work (does work after buttonClick emit)
        $this->emit('testEmit', 'Second (method render)');

        return view('livewire.second')->layout('layouts.guest');
    }

second.blade.php

<div>
    <button wire:click="$emit('testEmit')"> <!-- this works fine -->
</div>
<div>
   <button wire:click="buttonClick">test (calls method)</button>
</div>
<script>
//  Livewire.emit('testEmit') // this works fine
</script>

update: added more details/examples to Second.php and second.blade.php

like image 653
wivku Avatar asked Oct 29 '25 21:10

wivku


1 Answers

For anyone stumbling on this in the future, I found this to work:

//in *.blade file

<script>
    window.addEventListener("DOMContentLoaded", function () {
        Livewire.emit("emit_to_parent");
    });
</script>

//in livewire component

protected $listeners = ["emit_to_parent"];

public function emit_to_parent()
{
    $this->emit("foo");
}

For background, this issue explains why it doesn't work

Cannot emit events from mount method #598

like image 97
Sethmo011 Avatar answered Oct 31 '25 13:10

Sethmo011