Search code examples
javascriptsvelterouteparams

Adding query data to url in Svelte


I'm working on a SPA with Svelte. I have svelte-spa-router module installed. Nowhere seems to be documentation or examples how to add some object to your url.

This is easy in Vue:

router.push({ path: 'pathName', query: { someattribute: 'mygreatvalue' }})

In Svelte however the "push" only seems to support "location". I tried some vanilla function but it adds the data in the wrong place. My url looks like so: myniftyspa.com/#/thepage and I want:

myniftyspa.com/#/thepage/?someattribute=mygreatvalue

or:

myniftyspa.com/#/thepage/someattribute/mygreatvalue

it needs to stay on the page without reloading because I just want to store some data in the url this way. In the end it's about storing some ingredients information nested in an object that is being picked up after a revisit.


Solution

  • I figured something out as a "solution" that works for now. Maybe it's helping someone with the same issue.

    the object you want to be stored:

       const ingrParams = [
          {
            id: 308,
            gr: 100 
          },
          {
            id: 7,
            gr: 100 
          },
          {
            id: 233,
            gr: 80 
          }
        ];
    

    The snippet:

     push("/ingredients-to-nutrients/" + encodeURIComponent(JSON.stringify(ingrParams)));
     let p = JSON.parse(params.paramnameyousetinrouter);
    

    (push is an import of the svelte-spa-router module) note: you need to do an initial push at onMount or else this push will be seen as a page change.