Alain_92
Alain_92

Reputation: 55

Dynamic routing svelte

I am trying to build a simple blog with Svelte and Strapi v4 as backend. I have 2 pages : list of all posts page (no problem here) and the post page (problem here). For the list of posts, I manage to fetch my datas from Strapi using onMount. Works fine.

<script>
import { onMount } from "svelte";

let posts = []

onMount(async() => {
        const response = await fetch('http://localhost:1337/api/blogs')  
        posts = await response.json()
}) //etc...

The link to go to the specific post page [id].svelte works :

<p class="link"><a href={`/blog/${post.id}`}>En savoir plus >>></a></p>

But I get then an error. I don't manage to tell Svelte : fetch this specific id datas in the [id].svelte page. Using the below code in [id].svelte does not work, I get a 404 in the console.

<script>
import { page } from '$app/stores';
console.log(page)

I also tried with this method with no success :

    <script context="module">
export async function load(context = useContext(contextValue)) {
    console.log(context);

I am blocked and don't know how to move forward. Getting also lost between SvelteKit, Svelte... Thanks for your great help.

Here is the file tree of the route :

enter image description here

I am also using svelte-routing in my App.svelte file. I use this below code trying to tell Svelte to find my [id] page. But I always get a return saying the page is not found on the server...

<!-- App.svelte -->
<script>
  import { Router, Route } from "svelte-routing";

  import Index from "./App.svelte";
  import id from "./blog/[id].svelte";
 
  export let url = "";
</script>

<Router url="{url}">

  <Route path="blog/:id" let:params>
  <posteid id="{params.id}" /></Route>
  <Route path="/" component="{Index}" />
</Router>`

Upvotes: 3

Views: 4811

Answers (3)

Dwaipayan Chakroborty
Dwaipayan Chakroborty

Reputation: 302

this seemed to work for me, to fetch the path params

<Route
        path="property/:propertyId"
        let:params={propertyId}
        component={ViewProperty}
      />

and then in the component, add

   export let property;

note, propertyId here essentially, means the params that you'd wanna set

Upvotes: 0

Alain_92
Alain_92

Reputation: 55

Thank you @johannchopin. I can now access my [id].svelte page, using this route in my app.svelte :

<Route path="blog/:id" let:params/>

The link to the specific [id] works fine. Don't really know if "let:params" is the correct parameter to use here in my case.

However, I am still totally blocked whatever the method in trying to get the specific data of a specific [id].

Example 1 : does not work =>

 <script>
  export const load = async context => {
console.log('context', context)} 
</script>

I get nothing in the console, no 'context'.

Example 2 : does not work =>

       <script context = "module">
  export async function load({ fetch, page }) {
  const id = page.params.id 
  const res = await fetch(`http://localhost:1337/api/blogs/${id}`)
  const blogpost = await res.json()

  if (res.ok) {
    return {
      props: {
        blogpost
      }
    }
  }
}
   

Example 3 : does not work =>

<script>
      import { onMount } from "svelte";

let blogpost = []
    
    onMount(async () => {
      const response  = await fetch('http://localhost:1337/api/blogs/${id}')
        blogpost = await response.json()
        console.log(blogpost)
    }   )

</script>

No blogpost in the console. I think this is because "id" is not defined, but I don't know how to declare it, get this "id" and fetch this specific data actually.

Cannot see the solution. I am sorry for my ignorance.

Upvotes: 0

johannchopin
johannchopin

Reputation: 14844

in sveltekit you can get the route param id in the special load function and then fetch your content:

<script context="module">
  export async function load({ params, fetch, stuff }) {
    const blogId = params.id
    const url = `/your-api/blogs/${blogId}`;
    const res = await fetch(url)

    if (res.ok) {
      return {
        props: {
          content: await res.json()
        }
      }
    }

    return {
      status: res.status,
      error: new Error(
        `Error by fetching blog with id: ${blogId}!`
      )
    }
  }
</script>

Upvotes: 1

Related Questions