spaceavocado/svelte-router

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

kran6a opened this issue · 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?

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.

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}