php - Livewire - Force update view from component

I have a Livewire component and I want to do some async operations with it. However I could not figure out how to force refresh the update whenever I need.

To illustrate the problem, check out the example below.

Think like I'm trying to create a stop-watch. I'll click a button to start the stop-watch and everytime the $counter changes, I want to dispatch the value to my view.

class MyComponent extends Component {
   public $counter = 0;

   public function startTimer() {
       for ($i = 0; $i < 10; $i++) {
           $this->counter = $this->counter + 1;
           // I want to tell "send data to view/update data in view here"

           sleep(3);   
       }      
   } 
}
<button wire:click="startTimer">Start</button>
<h1>{{ $counter }}</h1>

This is a dummy example and I don't want to do it with polling.

Is there a way to tell to component something like $this->updateDataInView()?

Answer

Solution:

In Livewire you can use the magic method $refresh to manually refresh the view.

Option 1, in the view

<div>
    <button wire:click="$refresh">Reload Component</button>
</div>

See also a blog post on this.

Option 2, inside the component class

protected $listeners = [
    'refreshComponent' => '$refresh'
];

Here you need to emit the refreshComponent event, of course.

There is a Github discussion around this topic.

Source