Livewire component update with new data

36 views Asked by At

I need help with the Livewire component update based on the select dropdown.

class FutureTreeMapChart extends Component
{
    public $segment = 'N50';
    public $expiry = '2024-02-25';
    public $data;

    public function fetchTreeMap()
   {
          if (!empty($this->segment) && !empty($this->expiry)) {
          .....some codes to get data from DB.
          .... 
        $this-data = DB query.
}
         $this->dispatch('dataUpdated');
   }

    public function render()
    {
        $this->fetchTreeMap();
        return view('livewire.future.future-tree-map-chart');
    }
}

Now in the component blade file,

@script
    <script>
        $wire.on('dataUpdated', () => {

            var rawData = {!! $data->toJson() !!};

            console.log(rawData);
            console.log('updated');

        });
    </script>
@endscript

Whenever I change segment or expiry I can see there is an update request sent to the server and I get a response, but the problem is that rawData always logs for public $segment = 'N50';, Even if I select a different option for ```segment`` it logs for N50 only,

I did dd($this->data) on change, and it gets correct data from the database based on the selected segment, but on the script, it always prints one which is selected as public property,

To me, it looks like some issues in Lifecycle, but I could not point out why rawData always gets the default ```segment`` data,

What is wrong?

Thanks,

2

There are 2 answers

1
Aaron Dikko On
  1. public $segment;

  2. public $expiry;

Do not assign a default value for this two items, the select field should provide this information

0
Qirel On

Your problem is that you echo out the $data variable in PHP, so it's rendered initially.

Instead, you can fetch it from the $wire object.

@script 
<script> 
    $wire.on('dataUpdated', () => { 
        var rawData = $wire.data; 
        console.log(rawData); 
        console.log('updated'); 
    }); 
</script> 
@endscript