Skip to content

Instantly share code, notes, and snippets.

@ScottMaclure
Last active November 25, 2020 23:29
Show Gist options
  • Save ScottMaclure/640409646afcdff92c3818307b95b715 to your computer and use it in GitHub Desktop.
Save ScottMaclure/640409646afcdff92c3818307b95b715 to your computer and use it in GitHub Desktop.
/**
* A readable Svelte store is not modifiable outside the store.
* It's a "read-only" for those consuming it.
* This example uses JavaScript's Fetch() API together with AbortController().
* Handles a server going down and coming back up again, etc.
*/
import { readable } from 'svelte/store';
let controller = new AbortController();
const doUpdate = (set) => {
// TODO Haven't tested this yet (slow server response use case)
if (controller.is_fetching === true) {
// Wait
console.log('waiting on healthcheck..')
return true
}
controller = new AbortController() // TODO Another way to reset?
setTimeout(() => controller.abort(), 3000);
// TODO Env/Config.js etc?
fetch('http://127.0.0.1:8000/healthcheck', {signal: controller.signal})
.then(response => response.json())
.then(data => {
set(data)
})
.catch(error => {
console.error('healthcheck timeout/error: ' + error)
set({ 'error': error.toString() })
})
}
export const healthcheck = readable({}, function start(set) {
doUpdate(set) // fetch immediately
let interval = setInterval(() => {
doUpdate(set) // fetch every N seconds
}, 3000)
return function stop() {
clearInterval(interval);
}
})
<script>
import { onDestroy } from 'svelte';
import { healthcheck } from '../stores/healthcheck.js';
</script>
<h1>My Healthcheck Page</h1>
<p>Server healthcheck: <code>{JSON.stringify($healthcheck)}</code></p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment