In modern frontend development, efficient API interaction is crucial for building responsive and performant applications. This post dives into an optimized Axios configuration using TypeScript, providing a comprehensive guide to streamline your API requests. We’ll explore essential techniques such as interceptors, error handling, request cancellation, and more, ensuring your application handles API calls with grace and reliability.
Key Features & Capabilities:
- Centralized Axios Instance: Creates a pre-configured Axios instance with default settings like baseURL, timeout, Content-Type, and automatic cookie handling (withCredentials).
- Request Interceptors: Authentication: Automatically adds an authorization token to request headers if available (retrieved from localStorage).Cancellation: Generates and stores cancel tokens for each request, enabling request cancellation.
- Response Interceptors Error Handling: Centralized error handling to capture and standardize API errors, including status codes and response data.Cancellation Token Management: Removes cancel tokens after receiving a response or encountering an error.
- Typed Helper Functions:get<T>: Handles GET requests with proper typing for the response data.post<T, R>: Handles POST requests with separate types for request body and response data.put<T, R>: Handles PUT requests with separate types for request body and response data.deleteRequest<T>: Handles DELETE requests with proper typing for the response data.
- Request Cancellation: cancelRequest(url: string): Allows canceling specific requests using their URL.
- File Upload Handling: uploadFile<T>(url: string, file: File, config?: AxiosRequestConfig): Handles file uploads with progress tracking, providing console output of the upload percentage.
- Concurrent Requests: concurrentRequests<T1, T2>(url1: string, url2: string): Facilitates sending concurrent requests using axios.all and returns an array of responses.
- Offline Mode Handling Network Interceptor: Checks for internet connectivity before sending requests, rejecting requests if the user is offline.
- Error Handling: handle Error(error: any): Standardizes error responses, providing a consistent error object with message, status, and data.>
This configuration aims to improve the reliability, maintainability, and overall development experience by:
- Reducing boilerplate code for API interactions.
- Providing a consistent approach to handling errors.
- Enabling request cancellation for a better user experience.
- Simplifying file uploads with progress tracking.
- Facilitating concurrent requests for improved performance.
#TypeScript #API #Axios #JavaScript #Programming #WebDevelopment #CodeSharing #SoftwareDevelopment #OpenSource #React #FrontendDevelopment
Student at Shahid Beheshti University
3moعالی و کامل 👌