Closed rochdikhalid closed 2 years ago
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 Route
s 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.
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:
PostDetail.svelte:
Home.svelte: