M4TThys123 / JBI-Installatieservice

Ontwerp en Ontwikkeling van een Gebruiksvriendelijke Webapplicatie met API Integratie
https://jbistallatie.vercel.app/
0 stars 0 forks source link

Fetch `Prismic.io` data #6

Open M4TThys123 opened 1 year ago

M4TThys123 commented 1 year ago
M4TThys123 commented 1 year ago

Data Fetching/Loading

IMG_4976 Bron

Met de load functie kan je data vanuit de +page.js naar de +page.svelte sturen.

+page.svelte

<script>
    export let data;
    console.log(data)
    const { products } = data; 
</script>

<h1>Shop</h1>
{#each products as product}
    <h2>{product.title}</h2>
    <p>{product.description}</p>
{/each}

Best Practice

+page.js

export const load = async ({ fetch }) => {
    // Async Fetch 1
    const fetchProducts = async () => {
        const productRes = await fetch('https://dummyjson.com/products?limit=10');
        const productData = await productRes.json();
        return productData.products;
    };

    // Async Fetch 2
    const fetchUsers = async () => {
        const usersRes = await fetch('https://dummyjson.com/users?limit=10');
        const usersData = await usersRes.json();
        return usersData.users;
    };

    return {
        products: fetchProducts(),
        users: fetchUsers()
    };
};

Bad Practice

export const load = async ({ fetch }) => {
    // Fetch 1
    const productRes = await fetch ('https://dummyjson.com/products?limit=10')
    const productData = await productRes.json()
    const products = productData.products

    // Fetch 2
    const usersRes = await fetch ('https://dummyjson.com/users?limit=10')
    const usersData = await usersRes.json()
    const users = usersData.users

    return {
        products: products,
        users: users
    }
}

Prefetch

+layout.svelte

Voeg data-sveltekit-prefetch toe aan een <a></a>

<nav>
    <a href="/">Home</a>
    <a href="/shop" **data-sveltekit-prefetch**>Shop</a>
    <a href="/movies" **data-sveltekit-prefetch**>Movies</a>
</nav>