How to receive a variable from Livewire in a Javascript script?

I have a Livewire Component in app/Http/Livewire/Data.php

class Data extends Component
{
    public $data= 0;

    public function data()
    {
        $this->data= 100;
    }

    public function render()
    {
        return view('livewire.data');
    }
}

I have a view in resorces/views/livewire/data.blade.php I want to know how I can make use of the $data variable within a script found in this same view.

<div style="text-align: center">
    <button wire:click="data"> My buttom</button>
    <-- Here it's shown without problems -->
    <h1>{{ $data }}</h1>
</div>

<!-- Not shown here -->
<script>
    document.addEventListener('livewire:load', function () {
        var data = @this.data
        console.log(data) 
    })
</script>

It doesn’t show me the value of data when I doing console.log ()

1 Like

Hi, test with this code you will get it working, the event that you are listening fires during page load.
the code bellow will listen for component updates and will get the latest property changes.

document.addEventListener(“DOMContentLoaded”, () => {
Livewire.hook(‘element.updated’, (el, component) => {
var data = @this.data;
console.log(data);
})
});

Thank you! it works, but now it shows the variable twice.

Change livewire hook to message.processed, example bellow,
if the data show twice you are sending double request, add wire:click.prevent to the button to see if that helps.

document.addEventListener(“DOMContentLoaded”, () => {
Livewire.hook(‘message.processed’, (el, component) => {
var data = @this.data;
console.log(data);
})
});

1 Like

Thank you, is working fine!

1 Like