Here’s how Luwjistik’s front-end team simplified the complicated process of fetching data from APIs by creating a versatile and robust tool that handles various scenarios.
The Challenge: Handling Fetch Requests and Result Handling
Fetching data from an API is a common requirement in modern web development. However, handling repeated loading indicators, retrieving fetching statuses, and managing the need for re-fetching data can be challenging and time-consuming. In terms of writing code, these challenges often lead to code duplication, difficulty in controlling complexity, and worse and most frustrating for developers, code with poor readability.
<xmp>// example of the fetch api function on submitting data in a form
const doSubmitForm = async () => {
try {
// Show loading indicator
showLoadingIndicator()
// Process the fetched data
const response = await fetch('https://api.example.com/data')
await response.json()
// Show success message
showSuccessMessage('Data fetched successfully')
// Additional process after successful fetched data
setTimeout(() => {
// ...
}, 250)
} catch (error) {
// Show error message
showErrorMessage('Failed to fetch data')
console.log('Error fetching data!', error)
// Additional process when failed fetched data
// ...
} finally {
setTimeout(() => {
// Hide loading indicator
hideLoadingIndicator()
// Additional process every time fetched finishes running
// ...
}, 500)
}
}
doSubmitForm()</xmp>
"Complexity is your enemy. Any fool can make something complicated. It is hard to keep things simple."
Richard Branson
In the world of web development, it’s easy to fall into the trap of complexity. The above quote perfectly captures the essence of simplicity, which is also related to readability. And also, the quotation perfectly captures the heart of the Fetch Engine.
The Fetch Engine is a versatile and powerful tool that simplifies fetching data from an API. It provides a clean and efficient solution for handling API data retrieval. By abstracting away common patterns and providing customizable options, the Fetch Engine allows developers to retrieve data effortlessly, manage various scenarios effectively, simplify the code, and improve maintainability. Let’s see how the Fetch Engine can optimize the previous example code:
<xmp>const doSubmitForm = async () => {
// Process the fetched data
const response = await fetch('https://api.example.com/data');
await response.json();
};
// fetch engine options
const options = {
// The success & failed message that will be displayed
messages: {
success: 'Data fetched successfully',
error: 'Failed to fetch data',
},
// Function for toggling the loading indicator
customLoadingFn: () => {
toggleLoadingIndicator();
},
// Additional process after successful fetched data
successSubmissionFn: () => {
// ...
},
// Additional process when failed fetched data
failedSubmissionFn: (error) => {
console.error(error)
// ...
},
// Additional process every time fetched finishes running
finalSubmissionFn: () => {
// ...
},
};
fetchEngine(context, doSubmitForm, options);</xmp>
To address the challenges, the Fetch Engine provides a comprehensive solution that streamlines the data retrieval process and eliminates the need for repetitive code. By incorporating features such as loading indicator management, fetching status retrieval, and automatic re-fetching, the Fetch Engine simplifies API data retrieval and significantly reduces development time. Let’s delve into the specific problems solved by the Fetch Engine:
Repeated Loading Handling
Fetching data from an API typically involves displaying a loading indicator to inform users that the request is in progress. However, implementing loading indicators across multiple components or pages can result in repetitive code and increased maintenance efforts. With the Fetch Engine, you can easily incorporate loading indicators into your application using the customLoadingFn option. This function allows you to define how the loading indicator should be displayed and provides a centralized mechanism for managing loading states.
Retrieving Fetching Status
When fetching data to an API, retrieving the fetching status is essential to provide users with meaningful feedback. However, obtaining this status and handling success and error messages can take time and effort. The Fetch Engine simplifies this by giving customizable success and error messages through the messages option. You can specify the messages displayed when the fetch is successful or when an error occurs to eliminate the need to manually handle success and error messaging throughout your application, reducing code duplication and improving code maintainability.
Additional Processing Logic
Often, after a successful fetch or when an error occurs, additional processing logic needs to be executed, including tasks like updating UI components, triggering other API requests, or performing calculations based on the retrieved data. The Fetch Engine allows you to define these additional processing steps through the successSubmissionFn, failedSubmissionFn, and finalSubmissionFn options. These functions are called at the appropriate stages of the fetch process, enabling you to perform the necessary actions in a structured and controlled manner.
Code Reduction through Abstraction
The repetitive nature of loading handling, fetching status retrieval, and re-fetching can lead to code bloat and decreased maintainability. With the Fetch Engine, you can abstract away these common patterns and encapsulate them within a single, reusable function. This abstraction eliminates code duplication, reduces the overall complexity of your application, and promotes clean and maintainable code. By leveraging the Fetch Engine, you can focus on implementing business logic and delivering value rather than dealing with repetitive boilerplate code.
Conclusion
The Fetch Engine offers a powerful and efficient solution for handling API data retrieval while keeping things simple. Providing a streamlined workflow and customizable options enables you to simplify your codebase and eliminate unnecessary complexity. With the Fetch Engine, you can improve code maintainability, reduce duplication, and enhance the user experience of your applications.
By leveraging the Fetch Engine, you can focus on what truly matters: delivering high-quality software that solves real problems. Instead of getting tangled in the intricacies of repetitive fetch code, you can spend more time building valuable features and enhancing the overall functionality of your application. Say goodbye to code duplication and welcome a cleaner and more efficient approach to API data retrieval with the Fetch Engine.