Home > Software design >  Svelteki api fetch pages
Svelteki api fetch pages

Time:01-13

In short, I want to fetch data from diferents pages from one API I've made.

The API is https://joao-back-ecommerce-prod.herokuapp.com/store/ and as you can see I've multiples endpoints.

With svelte i'm trying to go from page to page in one click with increment function.

exemple:


<script context="module">
    export async function load({ fetch, page }) {
        const id = page.params.id;
        const res = await fetch(
            `https://joao-back-ecommerce-prod.herokuapp.com/store/products/?page=${id}`
        );
        const products = await res.json();
        console.log(products);

        if (res.ok) {
            return {
                props: {
                    products: products.results
                }
            };
        }
        return {
            status: res.status,
            error: new Error('Could not fetch the results')
        };
    }
</script>

<script>
    export let products;
    export let id = 1;

    const next = () => {
        id  ;
    };
</script>

<ul>
    {#each products as product}
        <li>
            {product.title} - {product.description}
            <a href={product.id}>hlmlll</a>
        </li>
    {/each}
    <button on:click={next}>Next</button>
</ul>

I want to go to next page when click on button next. I thought that with increment id 1 it will be work, but, it doesn't.

In the browser when I change the page number it works.

Any help?

CodePudding user response:

You are just changing a local variable, it does not affect the url. What you would do is navigate to the next page by changing the url.

There are two ways to do this:

import { goto } from '$app/navigation';
const next = () => goto(`/product/${id 1}`); // change to get correct path for you

or, a better way is to actually just link to the next page instead:

<a href="/product/{id 1}">Next</a>

The second option is preferred because you are in fact navigating for which you should use a link (buttons are for actions), it will also work if the user has javascript disabled.

SvelteKit will not actually go to the server and load a new page, it will just fetch the data from the load function and update accordingly, the user will not notice they are on a different page, only the url changes.

  •  Tags:  
  • Related