I have a specific app which should do the following:
I did a basic implementation in the following REPL: https://svelte.dev/repl/fcdce26dc0d843dbb4b394dcd2c838af?version=3.20.1
There are a couple of issues with this approach:
Job.svelte view should basically reset when you provide a new id, and clear out any previous poller, but now it's super awkward with a reactive statement at the bottompoller is cleared even though the handler is executing already. This causes multiple poller loops to occur (you can reproduce this by clicking through the job list at random intervals between 0 and 2 seconds)For this use case, what is a better way of implementing it (in Svelte)?
Thanks a lot!
The Job.svelte view should basically reset when you provide a new id, and clear out any previous poller, but now it's super awkward with a reactive statement at the bottom
Like a previous reply already pointed out, this is the Svelte way. It's awkward at first, until you realize it's very simple, handy and elegant.
There are two things I would improve in your code:
progress and chose to display progress[id], this way a late fetch reply will update in the background, but not interfere visually with your currently displayed jobsetInterval instead of multiple setTimeout for periodic polling<script>
export let id
let progress = {}
let poller
const setupPoller = (id) => {
if (poller) {
clearInterval(poller)
}
poller = setInterval(doPoll(id), 2000)
}
const doPoll = (id) => async () => {
console.log(`polling ${id}`)
progress[id] = await new Promise(resolve => setTimeout(() => {
resolve((progress[id] || 0) + 1)
}, 500))
}
$: setupPoller(id)
</script>
<div>
<p>
ID: {id}
</p>
<p>
Progress: {progress[id] || 0}
<p>
</div>
See this REPL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With