Search code examples
javascriptphplaravellaravel-livewire

Liveware value does not update in script tags


I have a problem with liveware. I'm building a slider sort of a thing with liveware, and my component duration is changing over time. The duration updates in the html when the component changes, but not in the script tags. So the liveware code is working fine, but how can I get it to have the updated duration in the script tags so the timeout works based on the updated component duration?

The duration per component may change like: 5, 7, 30 etc.

So I have a code like this:

    <section class="app-content">
        {{ $component['key'] }}
        {{ $component['duration'] }}
        @include('components.test')
    </section>

And this is my script code:

<script>
    document.addEventListener('livewire:load', function () {
        Livewire.on('nextComponent', duration => {
            console.log(duration);
            setTimeout(() => Livewire.emit('nextComponent', {{ $component['duration'] }} ), {{ $component['duration'] }} * 1000);
        })
        setTimeout(() => Livewire.emit('nextComponent', {{ $component['duration'] }}), {{ $component['duration'] }} * 1000);
    });
</script>

Solution

  • I fixed it with this:

    <script>
        window.addEventListener('newSlide', event => {
            setTimeout(() => Livewire.emit('nextComponent', event.detail.duration), event.detail.duration * 1000);
        })
    
        document.addEventListener('livewire:load', function () {
            setTimeout(() => Livewire.emit('nextComponent'), {{ $component['duration'] }} * 1000);
        });
    </script>
    

    And:

    $this->dispatchBrowserEvent('newSlide', ['duration' => $this->component['duration']]);