# Making the web Svelter with SvelteKit ### Part 2 - Pass data from Svelte Server to client [Back to part 1](part1_slides.html) --- ## Using the load()-function - The load()-function is available for use in: - +page.svelte - +page.js - +layout.svelte - +layout.js - +page.server.js - +layout.server.js - Depending on what you need to do, will determine which load()-function to use --- ## Using the load()-function
--- ## +server.js to create APIs - .server.js files create APIs with URLs determined by the directory-structure - HTTP GET is handled via the GET({ params, request, cookies })-function - HTTP POST is handled via the POST({ params, request, cookies })-function - HTTP PUT is handled via the PUT({ params, request, cookies })-function - HTTP DELETE is handled via the DELETE({ params, request, cookies })-function - A common pattern is to place these in a separate routes/api/**-directory --- ## API-handlers example ```svelte [] import { json } from '@sveltejs/kit'; export function GET({ request, cookies }) { const userid = cookies.get('userid'); //... logic return json(data); } export async function POST({ request, cookies }) { const { data } = await request.json(); //... logic return json({ id }, { status: 201 }); } export async function PUT({ params, request, cookies }) { const { done } = await request.json(); //... logic return new Response(null, { status: 204 }); } export async function DELETE({ params, cookies }) { const userid = cookies.get('userid'); //... logic return new Response(null, { status: 204 }); } ``` --- ## Loading images from +page.js ```svelte [] export function load({ params }) { return { photos: [ { id: 'IMGP4117.jpg', title: 'Valmue' }, { id: 'background1.jpg', title: 'Tyttebær' }, { id: 'IMGP4642.jpg', title: 'Tyttebær 2' }, { id: 'IMGP6801.jpg', title: 'Sommerfugl' } ] }; } ``` --- ## Available in +page.svelte via export let data; ```svelte [] export let data; ``` --- ## Using the data in the markup ```diff []
-
-
-
-
+ {#each data.photos as photo} +
+ {/each}
``` ```svelte []
{#each data.photos as photo}
{/each}
``` --- ## Onwards [part 3](part3_slides.html)