This is a example of a sveltekit app which renders an array of images from the unsplash json api utilizing some features of sveltekit.
Why Sveltekit #
I have followed svelte for a while & like the idea of no virtual DOM.
The sveltekit project is really interesting as it takes a lot of modern tools (eg: Vite HMR) & provides a framework to take advantage of modern features like mixing SSR with CSR & prefetching.
Rich Harris - Rethinking reactivity (2019)
Have Single-Page Apps Ruined the Web? (2021)
The Future of Svelte (Interview with Rich Harris)
SvelteKit's new filesystem-based router (Sep 2022)
Svelte Code #
The main code is pretty simple & the svelte docs have some really good examples.
Import variables from .env
using sveltekit $env/dynamic/public module
import { env as public_env } from '$env/dynamic/public';
Start with a fetch request in JS which returns json
async function fetchImages(searchTerm = 'neon') {
const imageRes = await fetch(`${api_url}&query=${searchTerm}`);
const imageData = await imageRes.json();
return imageData.results;
}
Use a form (with event handler) which returns searchTerm
<form on:submit|preventDefault={handleSubmit}>
<input bind:value={searchTerm} type="text" />
</form>
Use an event handler on submit of searchTerm
function handleSubmit() {
searchImages = fetchImages(searchTerm);
}
Use svelte logic within page to return a image component for each result in array
{#await searchImages}
<p>searching ...</p>
{:then images}
{#each images as image}
<img alt={image.id} src={image.urls.regular}/>
{/each}
{:catch error}
<p>ERROR: <span>{error}</span></p>
{/await}
This demonstrates how easy svelte makes it to create dynamic webapps.
I previously made a similar example project using vanillajs in 2018 to show you can do a lot with DOM manipulation & no virtual DOM.
Main Features #
Requirements #
Getting an API Key #
In order to make any requests you will need to signup to unsplash as a developer & request an API key.
Adding API Key to App #
Add unsplash developer key to .env
file in the base directory of the project.
PUBLIC_API_CLIENTID = "insert-api-key-here";
The source for this project is available on github.
References: fetch() / sveltekit / vite / promises / Unsplash API
Webmentions
No Comments Yet