Xanger's avatar

Paginate does not work with wire:init

I am just starting to implement livewire a few days ago and still need to understand some dynamics.

I put a wire:init in my project and it works correctly, but if I try to use paginate I get error:

class ProfileTimeline extends Component
{
    use WithPagination;

    public $member_id;
    public $readyToLoad = false;

    public function loadItems()
    {
        $this->readyToLoad = true;
    }

    public function mount($slug)
    {
        $this->member_id = $slug;
    }

    public function paginationView()
    {
        return 'livewire.pagination';
    }

    public function render()
    {
        return view('livewire.profile-timeline', [
            'item' => $this->readyToLoad
                ? LogsPublic::where('id_user', $this->member_id)->orderby('created_at','desc')->paginate('10')
                : [],
        ]);
    }
}

blade:

<div wire:init="loadItems">
[...]
	<div class="flex justify-center mt-2">
        {{ $item->links() }}
    </div>
</div>	

LOG.error: Call to a member function links() on array {

If I remove $item->links() the page loads correctly, however I need the paginate...

0 likes
5 replies
LaryAI's avatar
Level 58

The issue is that the $item variable is being set to an empty array when $readyToLoad is false. This causes an error when trying to call the links() method on an array. To fix this, you can check if $item is an array before calling the links() method. Here's an updated render() method:

public function render()
{
    $logs = $this->readyToLoad
        ? LogsPublic::where('id_user', $this->member_id)->orderby('created_at','desc')->paginate('10')
        : [];

    return view('livewire.profile-timeline', [
        'item' => $logs,
    ]);
}

And here's the updated blade file:

<div wire:init="loadItems">
    [...]
    <div class="flex justify-center mt-2">
        @if(is_array($item))
            {{ $item->links() }}
        @endif
    </div>
</div>
Xanger's avatar

It keeps returning the usual error....

Snapey's avatar

Why are you using wire:init and readyToLoad? Have you done it without and found a problem?

Snapey's avatar
Snapey
Best Answer
Level 122

The problem is caused by the use of links on an empty array.

Don't show the links if readyToLoad is false.

<div class="flex justify-center mt-2">
	@if($readyToLoad)
	        {{ $item->links() }}
	@endif
</div>
Xanger's avatar

@Snapey Thank you very much! I was trying all of them, and I hadn't thought about this....

Please or to participate in this conversation.