wannabe-laravel-dev's avatar

Efficient Infinite scroll using Livewire?

Are there any known techniques/methods for implementing infinite scroll or load more on scroll using Livewire without querying the database for all previous results?

All tutorials on the web seem to show exactly the same inefficient way of implementing it which is like this..

  • At first 10 results are loaded
  • When load more is called 20 results are loaded
  • Each time you load more it just adds 10 to the amount of results that are returned.

Instead of querying the database for the next 10 results it queries for all previous results.

0 likes
5 replies
pboivin's avatar

Hi there!

I've been using the technique you mention (load previous results + new page) and it's been fine with a few results, but obviously it starts to break down with a large number of items.

I started experimenting with an alternative solution that preloads all the item IDs, divided into pages (chunks), and then uses child components to render each page :

https://github.com/pboivin/livewire-load-more-poc

  • PostList - the main component doing the initial query
  • PostListItems - the child component rendering individual pages

Hope this can help!

P.

1 like
chrispage1's avatar

This is the same brutally inefficient technique unfortunately!

valentin_vranic's avatar

Hey. I came up with an idea/solution. You can like it or hate it, but this is what I can give you :D

Using, livewire 3 and alpineJs/vanillaJs solutions.

The view:

x-user-tile (in views/components)

@props(['user', 'bg'])

<div wire:key="{{ $user->id }}"
     style="background: {{ $bg }};
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #1f2937;">
    {{ $user->name }}
</div>

I'm using the laravel pagination, combined with livewire use WithPagination, WithoutUrlPagination; With this approach, I only append to the parent, preventing the growth of property, and querying the whole dataset using only the limit.

p.s. with livewire 4, there is/will be a solution for this: https://livewire.laravel.com/docs/4.x/islands#append-and-prepend-modes

1 like

Please or to participate in this conversation.