-
Notifications
You must be signed in to change notification settings - Fork 121
06: Loading Data with Fetch
The fetch API is a powerful and flexible tool in modern web development that allows you to make network requests, typically to fetch resources from a server. It's built into most modern web browsers and provides a more modern and flexible alternative to the traditional XMLHttpRequest for making HTTP requests. The fetch API returns a promise that resolves to the response to that request, whether it's successful or not.
The basic syntax of the fetch function looks like this:
fetch(url [, options]);-
url: The URL of the resource you want to fetch. This can be an absolute URL or a relative URL within your domain. -
options(optional): An object containing various configuration options for the request, such as headers, request method (GET, POST, etc.), and more.
When you call fetch, it initiates a network request to the specified URL. The response is returned as a promise. The promise resolves to the Response object representing the response to the request.
You typically use .then() to handle the response once it's available:
fetch(url)
.then(response => {
// Handle the response here
})
.catch(error => {
// Handle errors here
});The Response object returned by the promise contains various properties and methods that allow you to interact with the response data. You can access properties like status (HTTP status code), statusText (status message), headers (response headers), and more.
The response from the server is often in the form of raw data, such as JSON, text, or binary data. To work with this data, you need to parse it. For example, to parse JSON data:
fetch(url)
.then(response => response.json())
.then(data => {
// Work with the parsed data
})
.catch(error => {
// Handle errors here
});The .json() method on the Response object returns a promise that resolves to the parsed JSON data.
The fetch API handles both network errors and HTTP errors (e.g., 404 Not Found) using the .catch() block. If the request encounters a network error or if the response has a status code indicating an error (e.g., 404 or 500), the promise is rejected, and the error is caught in the .catch() block.
Applying the above to load the data we use the fetch function to send a GET request to the specified URL, "data/staff.json". The .then method is used to handle the response. We pass a callback function to response.json(), which asynchronously parses the response body as JSON and returns a promise containing the parsed JSON data.
The .json() method works directly on the response object returned by the fetch call. This method is a built-in part of the Fetch API and is designed specifically to simplify the process of extracting JSON data from the response. (It automatically performs the necessary JSON parsing, which is why you don't need to use JSON.parse()).
fetch("data/staff.json")
.then((response) => response.json())Here, we use another .then method to handle the parsed JSON data. The provided callback function takes the data as an argument. Inside this callback, we'll populate the table with the extracted data.
.then((data) => {
// ...
})Next we use document.getElementById("staffTable") to select the table element with the id "staffTable". This will be the container where we add rows for each staff member.
const staffTable = document.getElementById("staffTable");Within the forEach loop, we iterate through each item in the parsed data array. For each item, we create a new row (<tr>) element, along with two cells (<td>) for the name and email.
data.forEach((item) => {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
const emailCell = document.createElement("td");
// ...
});We set the textContent property of nameCell to display the concatenated full name using template literals (`${item.first_name} ${item.last_name}`). We set the textContent property of emailCell to display the email.
nameCell.textContent = `${item.first_name} ${item.last_name}`;
emailCell.textContent = item.email;We use the appendChild method to append the nameCell and emailCell to the row element. Then, we append the row element to the staffTable. This process is repeated for each staff member in the data array.
row.appendChild(nameCell);
row.appendChild(emailCell);
staffTable.appendChild(row);If any errors occur during the fetching or parsing of the JSON data, the .catch method will handle them. The provided callback function logs an error message to the console.
.catch((error) => {
console.error("Error loading JSON:", error);
});When using the Fetch API you are using a Javascript feature known as XHR (XMLHttpRequest). These calls can be seen in the Browser console's network tab. However, you when using the Fetch API to make network requests from a web page, you will encounter issues when testing your page locally using the file:// protocol instead of a web server with http://. This is due to a combination of security measures and the nature of how web browsers handle certain functionalities.
To overcome these issues and ensure accurate testing of your Fetch API code, it's recommended to run your test page on a local web server. You can use tools like live server in Visual Studio Code to serve your test page over http://localhost. This approach ensures that your page's origin is considered as http://localhost or a similar domain, which aligns better with how the Fetch API works in real-world scenarios.
There is plenty more you can do with fetch including sending data but this gives you a taste of what it can be used for.
Although not needed for the above example it is useful to be aware of JSON.parse() and JSON.stringify.
JSON.parse() and JSON.stringify() are methods provided by JavaScript's built-in JSON object for handling JSON (JavaScript Object Notation) data.
The JSON.parse() method is used to parse a JSON string and convert it into a JavaScript object. It takes a JSON-formatted string as its argument and returns a JavaScript object that corresponds to the data represented in the JSON string.
const jsonString = '{"name": "John", "age": 30}';
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // Outputs: John
console.log(parsedData.age); // Outputs: 30In this example, JSON.parse() takes the jsonString and converts it into a JavaScript object, allowing you to access its properties using dot notation.
The JSON.stringify() method is used to convert a JavaScript object or value into a JSON string. This is particularly useful when you want to send data to a server or store data in a file, as JSON is a widely supported data format.
const data = { name: "Alice", age: 25 };
const jsonString = JSON.stringify(data);
console.log(jsonString); // Outputs: {"name":"Alice","age":25}In this example, the data object is converted into a JSON string using JSON.stringify(), making it suitable for transmission or storage.
If you need to send data to the server, you can include it in the options object. For example, when sending data with a POST request:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})