A Scalable, Modular Approach to Managing API Calls and Errors in React Applications
This repository contains the source code for my tutorial on building a centralized error-handling system in React using Axios, custom hooks (useApi), and service modules. The goal is to simplify error management, improve maintainability, and provide a seamless user experience.
πΊ Watch the YouTube Tutorial:
Simplifying React Error Handling: Build a Robust Frontend System
π Free Udemy Course:
Master Centralized Error Handling in React
Looking for a deeper dive into the topic?
π Read my in-depth article here to learn about building a robust frontend error handling system with Axios and custom hooks.
- Centralized Axios Instance: Avoid repetitive configuration and simplify API requests.
- Global Error Management: Handle all errors consistently using Axios interceptors.
- Reusable Service Modules: Keep API logic modular and organized.
- Custom
useApiHook: Simplify state management for API calls (data, loading, error). - Scalable Architecture: A solid foundation for adding advanced features in the future.
git clone https://github.com/riyons/centralized-error-handling-react.git
cd centralized-error-handling-reactnpm installCreate a .env.local file in the root directory:
REACT_APP_API_BASE_URL=http://localhost:3000npm startA simple Node.js server is included in the backend folder to simulate API responses.
-
Navigate to the backend folder:
cd backend -
Install dependencies:
npm install
-
Start the server:
node app.js
The server will run on http://localhost:3000. Update the REACT_APP_API_BASE_URL in the .env.local file to point to this URL for local development.
- Purpose: Manages base URL, headers, and global error handling.
- Code: See
/utils/axiosInstance.js.
- Purpose: Parse errors and display user-friendly messages using
react-toastify. - Enhancements: Redirect unauthorized users, categorize errors, and log them efficiently.
- Purpose: Keep API logic modular and separate from components.
- Code: See
/services/productService.jsfor examples likegetProductsandcreateProduct.
- Purpose: Simplify API calls with centralized state management for
loading,error, anddata. - Code: See
/hooks/useApi.js.
-
Centralized Error Parsing
- Custom error messages defined in
/config/ERROR_MESSAGES.js. - Example:
const ERROR_MESSAGES = { 401: "Unauthorized. Please log in.", 500: "Server error. Try again later.", NETWORK_ERROR: "Check your internet connection.", };
- Custom error messages defined in
-
User-Friendly Notifications
- Display actionable messages using
react-toastify.
- Display actionable messages using
-
Axios Instance (
axiosInstance.js)- Centralizes API configuration and error handling
- Implements interceptors for global error management
- Example usage:
// Intercepts all responses and handles errors globally axiosInstance.interceptors.response.use( (response) => response, (error) => { // Converts technical errors into user-friendly messages const message = ERROR_MESSAGES[error.response?.status] || ERROR_MESSAGES.GENERIC_ERROR; toast.error(message); return Promise.reject(new Error(message)); } );
-
Service Layer (
productServices.js)- Abstracts API calls from components
- Provides reusable service functions
- Example:
const getProducts = (params) => axiosInstance.get("/products", { params }); const getCategories = (params) => axiosInstance.get("/categories", { params });
-
Custom Hook (
useApi.js)- Manages API call states (loading, error, data)
- Provides consistent error handling
- Usage example:
const { data, loading, error, request } = useApi( productServices.getProducts ); // request() triggers the API call and manages all states automatically
-
Page Components (
ProductsPage.jsx)- Implements the actual UI logic
- Uses the custom hook for data fetching
- Handles loading and error states
- Example:
const ProductsPage = () => { const { data: products, loading, error, } = useApi(productServices.getProducts); if (loading) return <LoadingMessage />; if (error) return <ErrorMessage error={error} />; return <ProductsList products={products} />; };
- Component calls
useApihook - Hook triggers service function
- Service uses
axiosInstance - Axios interceptors handle errors
- Error messages from
ERROR_MESSAGES.jsare displayed
I'm planning to expand the system with additional features, including:
- Retry Mechanism: Implement custom retry logic with exponential backoff to enhance reliability.
- Advanced Error Categorization: Improve error parsing for specific use cases, such as validation or server errors.
- Request Cancellation: Use Axios cancel tokens to prevent memory leaks on component unmounts.
Have suggestions or found a bug?
Feel free to open an issue or create a pull request on GitHub.
Did you find this helpful?
- π Star the repository!
- π¬ Share your feedback in the YouTube comments.
Happy coding! π