Home > OS >  Svelte break in each
Svelte break in each

Time:12-19

So i have a database that i recieve an array of objects(JSON) that i iterate over using each but if there are like a 1000 objects to iterate over then i don't want to make all of them appear at one i want a "page" mechanism where each page contains around 30 and then the next page contains the next 30 and so on and so on.

But in order to do this i would need to "break" in the each block.

If anyone has a better idea on how to do this then please share your idea/source since i don't think the implementation i came up with is very good.

CodePudding user response:

You could slice your big array to just iterate over the relevant objects in the each block.

Example (REPL)

<script>
    const database = Array.from({ length: 1000 }, (_, index) => ({
        id: index,
        text: Math.random().toString()
    }))
    const pageSize = 30;

    let offset = 0;
</script>

{#each database.slice(offset, offset   pageSize) as el (el.id)}
    <div>{el.text}</div>
{/each}

<button
    disabled={offset === 0}
    on:click={() => offset -= pageSize}
>
    Previous
</button>
<button
    disabled={offset   pageSize >= database.length}
    on:click={() => offset  = pageSize}
>
    Next
</button>
  • Related