HTTP Requests with Fetch API
The Fetch API is the modern way to send asynchronous HTTP requests in JavaScript. It provides a powerful and flexible feature set for making requests and handling responses.Basic Fetch Request
Using async/await
The more modern and readable approach:Aborting Fetch Requests
Aborting a fetch request in JavaScript is a common need. Thesignal option allows you to cancel requests at any time.
Using AbortController
To create a valid value for thesignal option, you can use AbortController.signal after creating a new instance of AbortController. Then, you can use AbortController.abort() to cancel the request at any time.
Timeout Pattern
Combine AbortController with a timeout:Request Options
GET Request
POST Request
PUT Request
DELETE Request
Handling Responses
Check Response Status
Different Response Types
Error Handling
Comprehensive Error Handling
Advanced Patterns
Retry Logic
Caching Responses
Parallel Requests
Sequential Requests
Best Practices
Always handle errors
Always handle errors
Network requests can fail for many reasons. Always use try/catch or .catch() to handle errors gracefully.
Check response.ok
Check response.ok
The fetch API doesn’t reject on HTTP errors (like 404 or 500). Always check
response.ok before processing the response.Use AbortController for cleanup
Use AbortController for cleanup
In React components or when navigation occurs, use AbortController to cancel pending requests and prevent memory leaks.
Set appropriate timeouts
Set appropriate timeouts
Don’t let requests hang indefinitely. Implement timeout logic to improve user experience.
Consider caching
Consider caching
For frequently accessed data that doesn’t change often, implement caching to reduce network requests.