Dispatching an event from an Action

Hi, should i dispatch an event from an action like this?
Action::make('prova')
->action(function () {
$this->dispatch('prova', ['prova']);
})
Action::make('prova')
->action(function () {
$this->dispatch('prova', ['prova']);
})
->dispatch('prova', ['prova']) doesn't work
15 Replies
krekas
krekas2y ago
Yes
Patrick Boivin
@teodino93 What is the issue exactly? What's not working?
awcodes
awcodes2y ago
Actions aren’t livewire components. Maybe
->action(function($livewire) {
$livewire->dispatch();
})
->action(function($livewire) {
$livewire->dispatch();
})
Also in lw3 dispatch events don’t use the array syntax for data. It should be named properties.
teodino93
teodino93OP2y ago
If I write
Action::make('prova')->dispatch('prova')
Action::make('prova')->dispatch('prova')
Nothing happens, i have to do like the original post to dispatch an event... I don't know if it's an error or it's correct to do like this.
Patrick Boivin
Have you tried the suggestion from awcodes? 👆
teodino93
teodino93OP2y ago
The code that i wrote on the original post works, I just wanted to be sure that should be the correct way to dispatch an event, since there is also a dispatch method.
LeandroFerreira
@awcodes , Sorry for tagging you, but do you know how we can dispatch events using the ->dispatch() method?
awcodes
awcodes2y ago
Looking at the code it should work like you're thinking. Maybe it's a conflict in this case with the name of that action being the same as the event that is being dispatched. It might be trying to call itself.
LeandroFerreira
I've tried with different names
#[On('custom-event')]
public function getCustomActionEvent()
{
dd('custom action triggered');
}

//works
Action::make('custom_action1')
->action(fn () => $this->dispatch('custom-event')),

// does not work
Action::make('custom_action2')
->action(null)
->dispatch('custom-event')
#[On('custom-event')]
public function getCustomActionEvent()
{
dd('custom action triggered');
}

//works
Action::make('custom_action1')
->action(fn () => $this->dispatch('custom-event')),

// does not work
Action::make('custom_action2')
->action(null)
->dispatch('custom-event')
awcodes
awcodes2y ago
With a null action, nothing happens on click anyway. Might have to ask Dan.
LeandroFerreira
yep, but without ->action(), ->action(null) this doesn't work
awcodes
awcodes2y ago
Could even be a situation where using dispatch is only meant to be used internally in action callbacks since it is probably not part of the caching that happens with actions.
LeandroFerreira
hum, ok I don't think it's an issue, but I didn't find a way to execute this. Maybe we can check with Dan on how we can use this. Thank you for your support!
teodino93
teodino93OP2y ago
Ok so we stick to action for now, thank you for the support!
KeyMe
KeyMe2y ago
im following this thread too, on the surface it seems like action's dispatch() method doesn't work while livewire's does

Did you find this page helpful?