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 Dataconst 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
Top comments (1)
Hey Lukeshiru, thanks for the correction I will update the article. I also think fetch is way neater π