Search code examples
sveltesapper

How to get location.state in svelte-sapper


I have a route pet/id and I'm trying to get the id and fetch my API with it to get information for an individual pet. How can I achieve that?

I've seen the preload function in the Sapper documentation but clearly this is not the proper way to achieve my goal because I get undefined when I'm trying to print a property of my pet object.

     <script context="module">
       export async function preload(page, session) {
         const { id } = page.params;

         const res = await 
         this.fetch(`http://localhost/api/public/api/pets/${id}`);
         const pet = await res.json();

         return { pet };
       }

    <svelte:head>
       <title>{pet.name}</title>
    </svelte:head>

    <h1>{pet.name}</h1> // Undefined


Solution

  • I found the problem. Since the function is asynchronous it needs some time to complete but I was trying to print the pet name immediately. What I did to fix it is:

        {#if pet} // Proceed to print the name when there is a pet
          <h1>{pet[0].name}</h1>
        {:else}
          <h4>Loading...</h4> // Show a loading message while the function is executing
        {/if}