An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
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 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
Original Link: https://dev.to/yaku/svelte-a-comprehensive-guide-to-developing-your-app-with-svelte-part-2-170j
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To