Getting Started with Svelte and Fetch Requests
This is a great way of getting into sveltekit and learn one of the most important functions in JavaScript.
Here we will just using the GET method of an http request but it opens the door with something simple.
We will be using the https://randomfox.ca as it has a great free api to get a Json that looks something like this
{
"image": "https://randomfox.ca/images/30.jpg",
"link": "https://randomfox.ca/?i=30"
}
First thing is first download a new copy of sveltekit, I recommend using the cloudflare version
This can be found here or https://developers.cloudflare.com/pages/framework-guides/deploy-a-svelte-kit-site
Just use this command
npm create cloudflare@latest -- my-svelte-app --framework=svelte --platform=pages
Make sure you choose the JavaScript option where possbile, we do not need any fancy linting or type checking
and to start it first run
npm i
Then
npm run dev
This will give a link to localhost:xxxx where you can open a web browser to and see what you are doing on a developement environment
Some things you need to know
A fetch request is made up of
fetch( url, { methods, headers, etc. } )
The method is optional and by default is get, headers are for specific needs such as a api has a autorization token needed to access it.
The url is where should you do the operation on
A fetch request will produce a promise, this is not the data we want, we need to let the api respond or await
There are two ways of handling a promise the .then() method or the await method
'Then's are generally set up like this
fetch(url)
.then(param => param.opertaion)
.then(param2 => {
thing1 = param2.operation1;
thing2 = param2.operation2;
})
And 'await's are set up like this
let res = await fetch(url);
let resA = await res.opertaion;
thingA = await resA.operation1;
thingB = await resA.operation2;
Generally we will use await as they make more sense to beginners and is a bit more clean, it is just nice to knwo that there are two.
What do we do with a raw request?
First thing you may noice if you try console.log it to the terminal is that it is garbage or it says Promise{...}
We need to ready the body of the response, generally that is where the good info is at, like our links and img urls
you can either do
// Just a string of the body
.text()
// A json/python array of the body
.json()
Now you can access it like a regular array using either ["link"] or .link to get the value from the key
Some final nice to haves
Because I am nice here is the style tag in its entireity for this example
Please notice that there is a selection part of the css and a action part that manipulates the selected tag
<style>
h1,
p {
text-align: center;
}
button {
display: block;
margin: 0svh auto;
}
img {
display: block;
margin: 0svh auto;
width: 40svw;
height: 70svh;
border: 1px solid black;
object-fit: contain;
}
</style>