Search code examples
phplaravellaravel-livewire

Livewire dispatchTo and dispatchSelf throw "does not exist" errors


I'm trying to communicate between a parent and child component from parent -> child using Livewire 3. The ultimate goal is, once an action finishes on the parent component, I want it to trigger the child component to refresh.

I've tried a couple of things, but I've come across something strange. I'm using Livewire v3.4.6 and I've tried using $this->dispatchSelf() within the child component, and $this->dispatchTo() in the parent component, and both of them throw Method App\Http\Livewire\Component::dispatchTo/dispatchSelf does not exist errors!

Does this not come packaged with Livewire? Do I need to import dispatchTo/dispatchSelf into the component using use? I assumed no considering dispatch() works fine??

The documentation suggests that it comes out of the box, so I'm really confused!


Solution

  • Livewire 3 has to() and self() methods to chain to dispatch():

    $this->dispatch('my-event')->to(AComponent::class);
    
    $this->dispatch('another-event')->self();
    

    on the js side the methods becomes dispatchTo and dispatchSelf

    $wire.dispatchTo("component-name", "my-event");
    
    $wire.dispatchSelf("another-event");
    

    The magic methods $dispatchTo and $dispatchSelf are also available:

    <button wire:click="$dispatchTo('component-name', 'my-event')">
       Dispatch To
    </button>
    
    <button wire:click="$dispatchSelf('another-event')">
       Dispatch Self
    </button>