I want to load up the view then update the variable data to stop the page taking ages to load (lots of data to load up). Is this possible with Laravel livewire?
I'm trying to get livewire to render the view and then update the public variables after the page has been loaded. In my case, I'll be getting data from an api so I want the user to see the page and then I can add some loading spinners whilst fetching the data.
However, from my test and looking at the livewire lifecycle my test variable doesn't update.
Example Livewire Controller
class Example extends Component
{
public $test;
public function mount()
{
$this->test = 'hi';
}
public function render()
{
return view('livewire.example');
}
public function hydrate()
{
$this->test = 'TEST1';
}
public function hydrateTest()
{
$this->test = 'TEST2';
}
public function dehydrate()
{
$this->test = 'TEST3';
}
}
Example Livewire Blade
<div>
<p>Hello World</p>
<p>{{ $test }}</p>
</div>
The lifecycle hooks said that dehydrate runs after render(), which means $test should = 'TEST3 but it stays as 'hi', my initial state.
There seems to be javascript hooks as well, like when the component has been initalised. But I'm not sure how to call the livewire functions or variables from there.
Does anyone know how to update livewire variables after the view has been rendered?
You could initialize the data after the page has rendered for the first time, though the wire:init
directive.
Your blade would look something like
<div wire:init="loadData">
<p>Hello World</p>
<p>{{ $test }}</p>
</div>
And you component would have a method loadData()
, where you do your calls to the API.
class Example extends Component
{
public $test;
public function mount()
{
$this->test = 'hi';
}
public function loadData()
{
$this->test = 'Data loaded';
}
public function render()
{
return view('livewire.example');
}
}
See the official documentation on deferred loading for more examples.