The Fetch API is a modern interface that allows you to make network requests similar to XMLHttpRequest. It provides a more powerful and flexible feature set to interact with resources over the network. This API is widely used for fetching data from servers and handling responses in web applications. Below are three diverse, practical examples showcasing how to use the JavaScript fetch API in various scenarios.
This example demonstrates how to fetch user data from a public API and display it on a webpage. It’s ideal for scenarios where you want to retrieve and display real-time information.
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
console.log(data);
const userList = document.getElementById('user-list');
data.forEach(user => {
const li = document.createElement('li');
li.textContent = `${user.name} - ${user.email}`;
userList.appendChild(li);
});
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
jsonplaceholder.typicode.com
is a free fake API for testing and prototyping.This example illustrates how to send data to a server using the POST method. It is useful in applications such as submitting form data or user-generated content.
const userData = {
name: 'John Doe',
email: 'john.doe@example.com'
};
fetch('https://jsonplaceholder.typicode.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
JSON.stringify
to convert the JavaScript object to a JSON string for the request body.This example showcases how to fetch data from multiple sources concurrently. This is particularly useful when your application needs to gather data from different APIs before rendering content.
const urls = [
'https://jsonplaceholder.typicode.com/users',
'https://jsonplaceholder.typicode.com/posts'
];
Promise.all(urls.map(url => fetch(url)))
.then(responses => {
return Promise.all(responses.map(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
}));
})
.then(data => {
const [users, posts] = data;
console.log('Users:', users);
console.log('Posts:', posts);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Promise.all()
is used to wait for all fetch requests to complete before proceeding.