In this article, I will guide you on how to use Fetch API in Javascript.
Note: I am using Free fake API for testing and prototyping for demo URL: JSONPlaceholder.
So, let's get started,
- Fetching Data with Get Requests - The simplest use case for the Fetch API is to fetch data from a server using a GET request.
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
This code fetches data from the specified URL and logs the response data to the console. The fetch() method returns a promise that resolves to a Response object. We then use the json() method on the response object to extract the JSON data from the response.
- Sending Data to Post Request - We can also use the Fetch API to send data to the server using a POST request.
fetch('https://jsonplaceholder.typicode.com/posts',{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
- Handling Errors - Network requests can fail for various reasons, such as a server error or a network connectivity issue. To handle errors in Fetch API, you can use the catch() method on the returned promise.
fetch('https://jsonplaceholder.typicode.com/posts/999')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
- Async/Await with Fetch API - The Fetch API also works well with the async/await syntax, which allows for cleaner and more readable code.
async function fetchUserData(userId) {
const response = await
fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
const data = await response.json();
return data;
}
fetchUserData(10)
.then(data => console.log(data))
.catch(error => console.error(error));
- Adding Headers to Fetch Requests - You can also add custom headers to your Fetch requests to provide additional information to the server.
const headers = new Headers();
headers.append('Authorization','Bearer token');
fetch('API URL', {
headers: headers
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));