Search code examples
phplaravellaravel-livewire

Update/refresh livewire blade using intermediate updates from component method?


I have a Livewire 3 component with a method that takes a while and I would like to the page to show the latest status.

I'm relatively new to this, so I may not understand binding / refresh well enough.
What I tried was:

<?php

namespace App\Livewire;

use Livewire\Component;

class TestUpdate extends Component
{
    public $status;

    public function mount() {
        $this->status = 'zero';
    }

    public function update() {
        $this->status = 'one';

        $this->dispatch('$refresh');

        sleep(3);

        $this->status = 'two';
    }

    public function render()
    {
        return view('livewire.test-update');
    }
}

and as Blade:

<div>

    <form wire:submit="update">
        <button type="submit">Update</button>
    </form>

    {{-- option 1 --}}
    <div>
        {{ $status }}
    </div>

    {{-- option 2 --}}
    <input type="text" wire:model="status" placeholder="nothing...">

</div>

But this shows zero before and during the action, and two afterwards.
What can be done so one is shown as well?


Solution

  • While Livewire is busy, it will not update the frontend. The dispatch happens after the method is finished. If you want to perform a long running task while keeping track of its status, it's suggested to queue a job and keep its progress in the database. This way you can use wire:poll to read the database and update the frontend.

    Other options are generally more hacky, such as having a JavaScript callback to trigger the update if status == 1.