skip to Main Content

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


  1. As $app/stores implies, page is a store. That means you need to subscribe to it in order to read the contained value.

    import { page } from '$app/stores';
    
    const getPageUrl = () => {
      let url;
      const unsubscribe = page.subscribe(_page => { url = _page.url; });
      unsubscribe();
      return url;
    }
    

    Svelte runtime lib provides a util function get to help you read store value, you can use that too.

    import { page } from '$app/stores';
    import { get } from 'svelte/store';
    
    const getPageUrl = () => {
      const _page = get(page);
      return _page.url;
    }
    
    Login or Signup to reply.
  2. This is a store, to read it you have to subscribe or use the get 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.

    import { page } from '$app/stores';
    import { derived } from 'svelte/store';
    
    export const currentUrl = derived(page, $page => $page.url);
    
    <script>
      import { currentUrl } from '$lib';
    </script>
    
    <div>
      {$currentUrl}
    </div>
    

    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.

    import { page } from '$app/stores';
    import { derived } from 'svelte/store';
    
    export const processUrl = derived(
      page,
      $page => suffix => $page.url + ' ' + suffix,
    );
    
    <script>
      import { processUrl } from '$lib';
    </script>
    
    <div>
      {$processUrl('!')}
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search