DEV Community

Yaku
Yaku

Posted on • Updated on

Svelte: A Comprehensive Guide to Developing Your App With Svelte - Part 2

Hi welcome to part 2 of the comprehensive guide to Svelte.

In this article, we will be learning how to fetch API data using Svelte. We will be using the GitHub API to fetch data about repositories.

First, we need to install the Svelte npm package.

$ npm install svelte

Next, we need to create a file called app.svelte.

`

GitHub Repository Data

const url = "https://api.github.com/repositories";

const request = new XMLHttpRequest();

request.open("GET", url, true);

request.onload = function() {
if (request.status === 200) {
const resp = request.response;

const data = resp.body.data;

console.log(data);

}
};
request.onerror = function() {
console.error("request failed: " + request.status);
};

request.send();

`
In the code, we first define the URL for the GitHub API. We then create a new XMLHttpRequest object. We open the GET request and set the URL. We also set the true parameter, which ensures that the request is made asynchronously.

We then define two functions, onload and onerror . onload will be executed when the request is loaded, while onerror will be executed if there is an error. We then send the request.

If the request is successful, we will get the response body. We will then extract the data from the body and log it to the console.

You can try running the code in your browser. You should see the data for all the repositories on GitHub.

Thanks for reading ☺️
Please follow me on git here GitHub.com/yakumwamba

Discussion (2)

Collapse
lukeshiru profile image
Luke Shiru

In 2022 you really don't need XMLHttpRequest, every supported browser out there already supports fetch, which has a way simpler API. Here's your code using fetch instead:

fetch("https://api.github.com/repositories")
    .then(response => response.json())
    .then(console.log)
    .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

You might notice is way shorter ... and that's because it is πŸ˜… ... if using promises directly is confusing, you can always use top level await like this:

try {
    const response = await fetch("https://api.github.com/repositories")
    const data = await response.json();
    console.log(data);
} catch (error) {
    console.error(error);
}
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
yaku profile image
Yaku Author

Hey Lukeshiru, thanks for the correction I will update the article. I also think fetch is way neater πŸ˜…