Module 57 : Fetching Data with fetch().
1. Introduction to fetch()
What is fetch()?
The fetch() method is a built-in JavaScript API used to make HTTP requests to servers. It is part of the modern JavaScript standard and replaces older techniques like XMLHttpRequest.
Syntax:
fetch(resource, options)
resource: The URL (or Request object) to fetch.
options: An optional object for custom settings (like method, headers, body).
2. The Basic Structure of fetch()
fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); // Parse JSON }) .then(data => { console.log(data); // Use the data }) .catch(error => { console.error('There has been a problem with your fetch operation:', error); });
1: Fetch JSON Data from Public API
Objective:
Fetch user data from the public API and display it on the webpage.
Steps:
Use this free API: https://jsonplaceholder.typicode.com/users
Create an HTML page with a button: "Load Users"
Use fetch() to get data and display name, email, and city.
HTML:
<button onclick="loadUsers()">Load Users</button> <div id="output"></div>
JavaScript:
function loadUsers() { fetch('https://jsonplaceholder.typicode.com/users') .then(res => res.json()) .then(users => { let output = '<h2>Users</h2>'; users.forEach(user => { output += ` <p><strong>${user.name}</strong><br> Email: ${user.email}<br> City: ${user.address.city}</p> `; }); document.getElementById('output').innerHTML = output; }) .catch(error => console.error('Error fetching users:', error)); }
Explanation:
.then(res => res.json()): Converts the HTTP response into a JavaScript object.
.catch(): Handles any error such as no internet or wrong URL.
4. Use Case: POST Request Using fetch()
Example: Submit form data using POST method.
const formData = { name: "John Doe", email: "john@example.com" }; fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }) .then(res => res.json()) .then(data => console.log('Success:', data)) .catch(error => console.error('Error:', error));
💡 Explanation:
method: 'POST': Specifies the HTTP method.
headers: Tells the server you're sending JSON.
body: Converts the JavaScript object to JSON string.
5. 2: Display Posts Dynamically
Objective:
Use fetch() to retrieve posts and render them in HTML using a dynamic approach.
<button onclick="getPosts()">Load Posts</button> <div id="posts"></div>
function getPosts() { fetch('https://jsonplaceholder.typicode.com/posts?_limit=5') .then(res => res.json()) .then(posts => { let output = ''; posts.forEach(post => { output += `<h3>${post.title}</h3><p>${post.body}</p>`; }); document.getElementById('posts').innerHTML = output; }) .catch(err => console.error('Error loading posts:', err)); }
6. Common Errors and How to Handle Them
Error Type
Cause
Solution
Network Error
No internet or bad URL
Use .catch() to catch it
Invalid JSON
Server returns bad format
Check response type
404 Not Found
URL incorrect
Validate the endpoint URL
Example of Handling 404:
fetch('https://example.com/data') .then(res => { if (!res.ok) { throw new Error(`HTTP error! Status: ${res.status}`); } return res.json(); }) .catch(error => console.error('Caught an error:', error));
7. Research Insights
Key Expert Tips:
Async/Await is Preferred for Readability
— Sara Drasner (JS Expert)
“Use async/await syntax for cleaner and readable fetch logic.”
Error Handling Is Critical
— Kyle Simpson (Author of "You Don’t Know JS")
“Always anticipate what can go wrong, even with simple fetch requests.”
Async/Await Version:
async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/posts/1'); if (!response.ok) throw new Error('Network response was not ok'); const data = await response.json(); console.log(data); } catch (error) { console.error('Fetch error:', error); } } fetchData();
8. Exercises
Exercise 1:
Fetch and display a single user's data when a button is clicked.
Task: Use https://jsonplaceholder.typicode.com/users/1
Goal: single fetch + DOM rendering
Exercise 2:
Create a form to submit data using POST with fetch.
Task: Take name and message input, then submit to https://jsonplaceholder.typicode.com/posts
Goal: POST requests and working with forms
9. 3: Building a Mini Weather App
Objective:
Use a weather API to fetch data and display current weather of a user-input city.
HTML + JavaScript:
<input type="text" id="city" placeholder="Enter city"> <button onclick="getWeather()">Get Weather</button> <div id="weather"></div> <script> async function getWeather() { const city = document.getElementById('city').value; const apiKey = 'YOUR_API_KEY'; const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`; try { const res = await fetch(url); if (!res.ok) throw new Error('City not found'); const data = await res.json(); document.getElementById('weather').innerHTML = `Temperature: ${data.main.temp}°C<br>Weather: ${data.weather[0].description}`; } catch (error) { document.getElementById('weather').innerHTML = error.message; } } </script>
10. Summary
fetch() is a powerful tool to get and send data from/to servers.
Works with Promises and supports all HTTP methods.
Handling errors and parsing data is essential.
Async/await provides cleaner code.
Public APIs offer great practice.
Quiz
res.json() return.
handle a failed fetch call.
HTTP method is used by default in fetch.
advantages of using async/await with fetch().
A fetch call to POST data to an API.
No comments:
Post a Comment