Centralize API calls in Web Application - A must-have guide
Learn how to centralize API calls in web applications so that you do not repeat the same code in multiple times. Gain solid control of your code.
Hey there! I'm Chhakuli, working as a Front-End developer for a while now. Today, I want to share with you how you can make your app a lot better by changing how you handle API calls. Don't worry if you're new to this stuff - I'll explain everything in simple terms.
As developers, we constantly deal with APIs to fetch or send data, and in larger applications, API management can easily become chaotic. If you’re working with a framework like Next.js, you already have a robust framework that supports both client-side rendering (CSR) and server-side rendering (SSR). This dual capability makes Next.js a perfect environment to centralize API calls, offering flexibility and simplicity.
The Common Problem
Picture this scenario: You have a large Next.js app. It's functional, but there's a recurring issue. Every time data needs to be fetched from the server (that's what an API call does), you find yourself writing repetitive code. It's like cooking dinner and having to get out all the pots and pans each time you want to make a meal. It becomes a real pain!
Here's what the code often looks like:
const getData = async () => {
try {
const response = await fetch('https://my-api.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
return data;
} catch (error) {
console.error('Oops, something went wrong:', error);
}
};
This code might be scattered all over the app. It's messy and hard to keep track of. Plus, if you want to change something (like how errors are handled), you'd have to change it in multiple places. Not fun!
My Light Bulb Moment
One day, in a code review session, I got feedback from my senior. It was kind of like making a special kitchen helper who always gets your pots and pans ready for you.
