osbornemj's avatar

Using Livewire (v3) to create a progress indicator: correct use of 'dispatch' and 'Laravel.on'?

I am writing an app that allows a user to process of list of items. Each item takes a while to process, and as each item is processed I'd like to update the page with the number that have been processed so far.

My current code (below) displays the page, and the submit button runs the process method, but the report of the "Number processed" remains 0. There is no indication of any error. I don't whether I have a small mistake,, or whether my whole approach is wrong!

Here is a minimal version.

Livewire component:

<?php

namespace App\Livewire;

use Livewire\Component;

class ProcessItems extends Component
{
    public $numberProcessed = 0;

    public function process()
    {
        for($i = 0; $i < 3; $i++) {
            sleep(1);
            $this->numberProcessed++;
            $this->dispatch('update-number-processed', numberProcessed: $this->numberProcessed);
        }
        dd('done');
    }

    public function render()
    {
        return view('livewire.process-items');
    }
}

Blade:

<div>

    <form method="POST" wire:submit="process()" method="POST">
    <div class="pt-4">
        <x-primary-button class="ml-0">
            {{ __('Submit') }}
        </x-primary-button>
    </div>
    </form>

    <div id="reportNumberProcessed">
			Items processed: 0
    </div>

    @script
    <script>
        document.addEventListener('livewire:init', () => {
            Livewire.on('update-number-processed', (event) => {
                document.getElementById("reportNumberProcessed").innerText = 'Items processed: 1';
            });
        });
    </script>
    @endscript

</div>

I want the page to report the number processed, but as a first step I am just trying to get it to change the 0 to a 1.

0 likes
1 reply
osbornemj's avatar

After more tests, my conclusion is that the Blade file gets refreshed only when the process() loop is complete, which means that the answer to the question is that the whole approach is wrong.

Please or to participate in this conversation.