thepanda wrote a reply+100 XP
2mos ago
thepanda liked a comment+100 XP
2mos ago
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.
class InfiniteScroll extends Component
{
use WithPagination, WithoutUrlPagination;
public const int PER_PAGE = 9;
public int $pageNumber = 0;
public array $colors = [
'#FF6B6B',
'#FFD93D',
'#6BCB77',
'#4D96FF',
'#B28DFF',
'#FF8E72',
'#00C2A8',
'#FFB3C1',
'#A7C7E7',
];
public function loadMore(): void
{
$this->nextPage();
$html = '';
foreach ($this->users as $i => $user) {
$html .= view('components.user-tile', [
'user' => $user,
'bg' => $this->colors[($i + 1 * self::PER_PAGE) % count($this->colors)],
])->render();
}
$this->dispatch('loadMore', ['html' => $html]);
}
#[Computed]
public function users()
{
return User::query()
->orderBy('id')
->paginate(self::PER_PAGE);
}
}
The view:
<div x-data="infiniteScroll">
<div style="min-height: 100vh; display: flex; align-items: center; justify-content: center;">
<div style="display: grid; grid-template-columns: repeat(3, 120px); grid-auto-rows: 120px; gap: 16px;"
wire:ignore
id="infiniteScroll">
@foreach ($this->users as $user)
@php
$bg = $colors[$loop->index % count($colors)];
@endphp
<x-user-tile :user="$user" :bg="$bg"/>
@endforeach
</div>
</div>
<div x-intersect="$wire.loadMore()"></div>
</div>
@script
<script>
Alpine.data('infiniteScroll', () => ({
init() {
Livewire.on('loadMore', (detail) => {
const container = document.querySelector('#infiniteScroll');
let block = detail[0]
container.insertAdjacentHTML('beforeend', block.html);
})
}
}))
</script>
@endscript
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
thepanda liked a comment+100 XP
3mos ago
Wayback Machine to the rescue! :)
https://web.archive.org/web/20111006164813/http://laravel.com/