spaceavocado/svelte-router

Store Router not updating

arthurgermano opened this issue · 2 comments

Hi there.. the router store is not updating or reacting..

My guess that is not creating an object or array brand new.. causing Svelte not realizing that the object/store has changed.
Screenshot from 2020-05-14 13-22-37

Anyway.. many thanks!
=)

Any idea how to solve this issue?

When I added the router import to the template in the file svelte-router-template/src/js/app.svelte where createRouter is called but $router appears always as undefined:

<script>
//...
  import createRouter, {ROUTER_MODE, router} from '@spaceavocado/svelte-router';
//...
  setInterval(() => {
    console.log($router)
  }, 2000);
</script>

$router provides only the router itself, it won't update when the router object mutates, as far as I understand. You can use the onNavigationChanged method to actually listen for navigations. I did it like this:

let unregister = $router.onNavigationChanged((from, to) => { /* do stuff */ })

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

I also needed to access the router in the same file in which I created it, though (in order to add a navigation guard and error handler), so I used the following helper function:

function getStoreValue (store) {
  let value
  store.subscribe(v => (value = v))()
  return value
}

(Note the extra () which unsubscribes again immediately.)

I then did this, using the return value of createRouter in getStoreValue(router) instead of $router:

const router = createRouter({ /* routes here */ })

getStoreValue(router).navigationGuard((from, to, next) => { /* navigation guard here */ })