I’m trying to create a reusable function that uses data from the current URL to generate some output. However, when I do the following:
// reusableScript.js
import { page } from '$app/stores';
export default () => {
return page.url
}
<!-- Component.svelte -->
<script>
import { script } from '$lib';
const url = script()
</script>
<div>
{url}
</div>
The value url
is always undefined. What am I understanding wrong?
2
Answers
As
$app/stores
implies,page
is a store. That means you need to subscribe to it in order to read the contained value.Svelte runtime lib provides a util function
get
to help you read store value, you can use that too.This is a store, to read it you have to
subscribe
or use theget
utility function, but this will lose reactivity, so I would not recommend this, unless you just want to read the value once.Otherwise export a new
derived
store that just gets the URL and then use it via$
-notation. E.g.If you need a function that processes the URL which requires parameters, you can create a derived store that returns a function instead, e.g.