svelte-router icon indicating copy to clipboard operation
svelte-router copied to clipboard

$router.push() and $route.replace() do not update the destination component route prop when the source and destination component are the same

Open kran6a opened this issue 4 years ago • 2 comments

Navigating (programatically and manually) from an url like https://example.com/myComponent/param1 to https://example.com/myComponent/param2 is not triggering myComponent updates. Doing a simple

<script>
  export let url;
  console.log(url);
</script>

Logs the first URL once.

Is this a Svelte shortcoming or a bug? Is there any workaround?

kran6a avatar Oct 12 '20 20:10 kran6a

I have a super dirty workaround:

  let routerFix = false
  let unregister = $router.onNavigationChanged((from, to) => {
    if (from && to && from.name === to.name) {
      console.log('(router fix)')
      routerFix = true
      tick().then(() => (routerFix = false))
    }
  })

  onDestroy(() => {
    unregister()
    unregister = null
  })

...and instead of <RouterView /> I have this:

<svelte:component this={routerFix ? Dummy : RouterView} />

...with Dummy coming from an empty file Dummy.svelte.

This essentially forces a complete reinstantiation of the component when switching between routes (swapping the router view for an empty component for a tick) that would otherwise use the same component.

CherryDT avatar Dec 15 '20 12:12 CherryDT

A better workaround now that {#key} is supported in Svelte:

  let navCount = 0
  let unregister = $router.onNavigationChanged((from, to) => {
    navCount++
  })

  onDestroy(() => {
    unregister()
    unregister = null
  })
{#key navCount}
  <RouterView />
{/key}

CherryDT avatar May 02 '22 09:05 CherryDT