I'm making a web application using Vite SvelteKit. I know that SvelteKit is currently in a development state, but I wonder if this error could be fixed in anyway in my code. Everything works just fine except this: I have a simple component, in which I import an array of objects which I iterate using each. I want to reverse the array before iteration, in order for the each construct to show the elements from the last one to the first one:
import { w, p } from '../../js/data.js'
let wRev = w.reverse()
{#each wRev as article, i}
<article>
{article.title} {article.author} {article.data}
</article>
{/each}
The data.js array of objects is very simple:
let w = [{title: ..., author: ..., data: ...}, {...}]
Now SvelteKit doesn't render the reverse operation in time. I'm using Vite, so I use automatic hot-reload (automatic page reload on save). The app is showing the array in the natural (not reversed) order. If I MANUALLY reload the page, it shows the reversed array. With ctrl s, browser shows:
- item 1
- item 2
- item 3
Same browser tab, manual reload, it correctly shows:
- item 3
- item 2
- item 1
then, crtl s after an edit somewhere in the code, then again item 1, item 2, item 3.
This issue only happens with this each rendering, other stuffs are rendered correctly in time. I wonder if:
- SvelteKit isn't able to reverse the array in time for Vite/hot-reloading to show it. Actually, the array is composed by 20-30 objects, it's not that large
- I can apply some strategy in order to load chunks of the array and load the others by pressing the common "more" button
CodePudding user response:
The problem is, that the imported data is mutated. So every time the code of the page is executed on hot-reload, the array is reversed. On initial load it will always be consistent but after that it will flip back and forth.
I would recommend not mutating the source data by creating a local copy first:
let wRev = w.slice().reverse()