As a fullstack web developer, you have an array of tools and technologies at your disposal to build websites that are efficient, dynamic and user-friendly. One of these tools that can help you better the user experience is fetch API
.
Suppose we have an input field where a user inputs the title of a blog post, and we want to generate a summary of the post based on the title. We can do this without the page refreshing, with the use of fetch()
API.
Here's how fetch()
API can be used to achieve this:
fetch('https://api.example.com/summary?title=' + title)
.then(response => response.text())
.then(data => {
// Update the UI with the summary
summaryElement.innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
});
In the code snippet above, we first initiate a fetch request to the backend that generates a summary of the blog post based on the title. The then()
method is used to update the UI with the response data received from the request.
However, what if the backend API is unavailable or the request fails for some reason? In such cases, the catch()
method will handle the error and keep the UI state consistent.
By using fetch()
API in your web development projects, you can create a smoother and more responsive user experience.
Here is a more complete example with HTML and JS:
<input type="text" id="blogTitle" placeholder="Enter blog title">
<button id="getSummary">Get Summary</button>
<div id="summary"></div>
<script>
const titleElement = document.getElementById('blogTitle');
const summaryElement = document.getElementById('summary');
const getSummaryButton = document.getElementById('getSummary');
getSummaryButton.addEventListener('click', () => {
const title = titleElement.value;
fetch('https://api.example.com/summary?title=' + title)
.then(response => response.text())
.then(data => {
// Update the UI with the summary
summaryElement.innerHTML = data;
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
In this code, we added two event listeners:
- one to listen for a click on a fetch button
- another to listen for the Enter key to be pressed to trigger a fetch request as well.
This code is meant to illustrate one use case for the fetch()
API, you can use it for many other purposes when building web applications.