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
render()
menthod. – Digvijay