1
votes

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

1
Try emitting under render() menthod.Digvijay
that did not work. It would call the emit in render only after calling a method. I will update the example the above to show the details.wivku
Did you ever get this working @wivku? I'm in the same situationJohn Cliven
No, situation is unchanged.wivku

1 Answers

0
votes

In such case, I would suggest to keep emit code in one function only.

public function mount()
{
    $this->buttonClick();
}

public function render()
{
    $this->buttonClick();
    return view('livewire.second')->layout('layouts.guest');
}

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