In SvelteKit, I get "Subscribed" and "Unsubscribed" logged to the console each time I navigate between the /first and /second routes. I want to have the readable's start function run only once for each user who visits the website - allowing me to store fetched data that doesn't change often.
// stores.ts
import { readable } from 'svelte/store'
const { VITE_WEB_URL } = import.meta.env
export const message = readable('', set => {
console.log('Subscribed')
const fetchMessage = async () => {
const url = `${VITE_WEB_URL}/api/message`
const response: Response = await fetch(url)
return await response.text()
}
fetchMessage()
.then(set)
.catch(err => console.error('Failed to get message', err))
return () => {
console.log('Unsubscribed')
}
})
<!-- /routes/first.svelte -->
<script>
import { message } from '../stores'
</script>
<h1>First: {$message}</h1>
<a href="/second">Second</a>
<!-- /routes/second.svelte -->
<script>
import { message } from '../stores'
</script>
<h1>Second: {$message}</h1>
<a href="/first">First</a>
As I navigate between pages/routes in SvelteKit, unsubscribe is called so the next page/route invokes the start function as the "first" subscriber.
How can readable stores be shared across multiple pages/routes without re-running the start function? I've heard suggestions about using the template but have never seen an example.
Would the template get the store value and pass it as props to components or simply prevent the store from having a "last subscriber" (effectively keep the door open)?