I have a simple Livewire component that lists users:
class UserListComponent extends Component
{
use WithPagination;
protected $listeners = ['refreshComponent' => '$refresh'];
public $search = '';
public $orderBy = 'id';
public $orderAsc = true;
public $perPage = 10;
public function render()
{
return view('livewire.admin.user-list-component',[
'users' => User::search($this->search)
->orderBy($this->orderBy, $this->orderAsc ? 'ASC' : 'DESC')
->simplePaginate($this->perPage)
]);
}
}
and a component that adds users:
public function addUser()
{
// validate data
$validatedData = $this->validate();
// generate random password
$bytes = openssl_random_pseudo_bytes(4);
$password = bin2hex($bytes);
// create user
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => Hash::make($password),
]);
event(new Registered($user));
// assign user role
$user->attachRole('user');
$this->emitTo('UserListComponent', 'refreshComponent');
}
As you can see, at the end of the addUser()
function I emit an event to the UserListComponent and have a listener set up in that component to refresh it, so that when a user is added the list of users automatically updates. However, it doesn't work. If I refresh manually I can see that the user is added to the database and display just fine, but the component refreshing does not happen, and no error is thrown.
Any ideas?
CodePudding user response:
From what I see the best way is to use full class name so instead of:
$this->emitTo('UserListComponent', 'refreshComponent');
you should use:
$this->emitTo(\App\Http\Livewire\UserListComponent:class, 'refreshComponent');
(of course update namespace if you have UserListComponent
in other namespace)