What you need is what they call Chunks, which is basically to divide a list into smaller lists of the maximum size defined. To do this, just use the method slice
of Array
to get each slice of your complete list. For ease, I have created a generator that will iterate over the sub-lists:
function* paginate(list, size) {
for (let i = 0, j = list.length; i < j; i += size) {
yield list.slice(i, i+size)
}
}
const eventos = [
'Evento 01',
'Evento 02',
'Evento 03',
'Evento 04',
'Evento 05',
'Evento 06',
'Evento 07',
'Evento 08',
'Evento 09',
'Evento 10',
'Evento 11',
'Evento 12'
]
const paginas = paginate(eventos, 4)
for (let pagina of paginas) {
console.log(pagina)
}
So, all you have to do is increase the logic that when the user presses the "See More" button, you search for the next value of the generator and add to the list of elements.
function* paginate(list, size) {
for (let i = 0, j = list.length; i < j; i += size) {
yield list.slice(i, i+size)
}
}
const eventList = [
'Evento 01', 'Evento 02', 'Evento 03', 'Evento 04',
'Evento 05', 'Evento 06', 'Evento 07', 'Evento 08',
'Evento 09', 'Evento 10', 'Evento 11', 'Evento 12'
]
const list = document.getElementById('lista')
const button = document.getElementById('btn')
const pages = paginate(eventList, 4)
button.addEventListener('click', function() {
const page = pages.next()
const events = page.value
if (page.done) {
this.disabled = true;
return;
}
for (let event of events) {
list.innerHTML += `<li>${event}</li>`
}
});
<ul id="lista"></ul>
<button id="btn">Ver Mais</button>
Do you want to make this pagination on client or server?
– Sergio
In client, because I do not have access to the API code.
– wDrik