mefechoel / svelte-navigator

Simple, accessible routing for Svelte

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to make a dynamic route with Svelte and svelte-navigator?

rochdikhalid opened this issue · comments

I'm new to Svelte and I'm using svelte-navigator as a router. I could pass a fetch and make an API call to read all posts. But, I'm getting stuck on how to create a dynamic route that goes to a specific post to read it, edit it, and delete it later. Here is my code and I really appreciate your help;

routes/index.svelte:

<Route path="posts/*">
   <Route path="/">
      <Home />
   </Route>
   <Route path=":id"> <PostDetail /> </Route>
</Route>

PostDetail.svelte:

    export let post = [];

    onMount(async () => {

        const response = await fetch(`http://localhost:8000/posts/${post.id}/`)
        post = await response.json()

    });

Home.svelte:

    let posts = [];

    onMount(async () => {
        const response = await fetch(`http://localhost:8000/posts/`)
        posts = await response.json()
    });
    
   <div class = "col-md-8">
       {#each posts as post }
            <article class="card mb-3">
                <h4 class="card-title">
                     <Link class = "text-dark" to = {`/posts/${post.id}`}> { post.name } </Link>
                </h4>
                <p class="card-text text-break"> { post.description.slice(0, 250) } ... </p>
            </article>
       {:else}
           <p class = "text-center"> Loading ... </p>
       {/each}           
   </div>

Hello there! The index and Home component seem just fine, but in the PostDetail, you're not accessing the posts id correctly. You can use the useParams hook to access the id url parameter:

<!-- In PostDetail.svelte -->
<script>
  import { useParams } from "svelte-navigator";

  // useParams returns a store containing the url params
  const params = useParams();

  // Note that you don't need the export here, as this isn't a prop
  let post = [];
  onMount(async () => {
    // Get the id from the path parameter `:id`
    const { id } = $params;
    // Then do what you did before
    const response = await fetch(`http://localhost:8000/posts/${id}/`)
    post = await response.json()
  });
</script>

<!-- Use the `post` array here... -->

You can also access the id using the Routes slot properties or by passing it a component prop (see documentation for Route component).

Thank you @mefechoel for your help. Now, I understand. I will use what you mentioned to access the id correctly.