Array Property Losing Records after Update
I am attempting to get familiar with Livewire's states (if that is even the correct term) regarding an array or collection of Records.
When the array is updated it appears to lose the previous records. Strangely the array's length seems to be correct but the output on the blade template side is not showing what I would expect.
I'm sure I'm simply missing something trivial and some help would be appreciated.
<?php
namespace App\Http\Livewire;
use App\Models\Artwork;
use Livewire\Component;
class Counter extends Component
{
public $count=0;
public $artworks=[];
public function increment(){
$this->count++;
array_push($this->artworks, Artwork::inRandomOrder()->first());
}
public function render()
{
return view('livewire.counter');
}
}
<div>
<p>count:{{$count}}</p>
<button wire:click="increment">+</button>
<hr>
@foreach($artworks as $artwork)
<li>{{$artwork->title ?? 'obj is null'}}</li>
@endforeach
</div>
With the first update, via the button click I can see a $artwork->title properly output.
BUT, additional clicks seems to nullify any previous records in the array.
Output becomes:
obj is null
obj is null
obj is null
Autem Dicta Sunt Ut Tempore Exercitationem
So livewire is two way. Your data is getting passed back and forth... php to javasctipt then back again. So you second round, the model is pass back from the view and now it's become an array.
** Edit: the above isn't entirely accurate. Better said, from the docs...
How the he*k does this work?
- Livewire renders the initial component output with the page (like a Blade include). This way, it's SEO friendly.
- When an interaction occurs, Livewire makes an AJAX request to the server with the updated data.
- The server re-renders the component and responds with the new HTML.
- Livewire then intelligently mutates DOM according to the things that changed.
So $artwork->title no longer works when it gets return to the view. Run this code and have a look... as it dumps out the model then the next pass its an array.
<div>
<p>count:{{$count}}</p>
<button wire:click="increment">{{ $count }}+</button>
<hr>
@forelse($artworks as $artwork)
<li wire:key="$artwork['id']">
{{ $artwork['name'] ?? 'obj is null'}}
@dump($artwork)
</li>
@empty
<li>nothing yet</li>
@endforelse
</div>
Please or to participate in this conversation.