url-routingsvelte

Get current path in svelte-routing


I'm trying to access the current route in order to conditionally redirect visitor incase the current route is "/". The way I have set up right now the redirection happens at any route if you type it in the addressbar. The only candidate solution I have right now is creating a store that holds the current path and using that store to set up the condition to navigate only if the store value is "/". But I am wondering if there is a more efficient way to do this?

here is app.svelte

<script>
  import {Router, navigate, Route} from "svelte-routing";
  import { user, loading } from "./lib/store";
  import Authentication from "./features/authentication/Authentication.svelte";
  import Notes from "./features/notes/Notes.svelte";
  import Read from "./features/notes/components/Read.svelte";
  import Create from "./features/notes/components/Create.svelte";
  import Folders from "./features/folders/Folders.svelte";
  
  //i want to do if(!$loading && path="/") below
  $: if(!$loading) {
    if($user) navigate("/folders");
    else navigate("/authenticate");
  }
</script>
{#if $loading}
  loading..
{/if}
<Router>
{#if $user}
<Route path="/notes/read/:id" let:params>
  <Read id={params.id} />
</Route>
<Route path="/notes/create" component={Create} />
<Route path="/notes" component={Notes} />
<Route path="/folders" component={Folders} />
{:else}
  <Route path="/authenticate" component={Authentication} />
{/if}
</Router>

I have tried using useLocation to get the current path. unfortunately since App.svelte isn't a child of the router that doesn't work and the function is returning undefined.


Solution

  • I found using window.location.pathname to be the most intuitive solution in this case!

    const path = window.location.pathname;
    $: if (!$loading && path == "/") { 
      if ($user) navigate("/folders");
      else navigate("/authenticate");
    }