JAVASCRIPT

Robust Data Fetching with Async/Await and Error Handling

Learn to fetch data from APIs reliably using async/await, including proper error handling, loading states, and cancellation for web applications.

async function fetchData(url, signal = null) {
  let data = null;
  let error = null;
  let isLoading = true;

  try {
    const response = await fetch(url, { signal });
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    data = await response.json();
  } catch (err) {
    if (err.name === 'AbortError') {
      console.log('Fetch aborted.');
    } else {
      error = err.message;
      console.error('Error fetching data:', err);
    }
  } finally {
    isLoading = false;
  }

  return { data, error, isLoading };
}

// Example usage:
const abortController = new AbortController();
const { signal } = abortController;

(async () => {
  console.log('Fetching posts...');
  const { data, error, isLoading } = await fetchData('https://jsonplaceholder.typicode.com/posts/1', signal);

  if (error) {
    console.error('Failed to fetch:', error);
  } else if (data) {
    console.log('Fetched data:', data);
  }
  console.log('Is loading:', isLoading); // Will be false here
})();

// To abort a request after a delay (e.g., if component unmounts or user navigates away)
// setTimeout(() => abortController.abort(), 5000);
How it works: This snippet demonstrates how to perform robust data fetching from an API using JavaScript's async/await syntax. It includes a `try-catch` block for error handling, checking `response.ok` for HTTP errors, and integrating `AbortController` for request cancellation. This pattern is crucial for managing network requests gracefully, preventing memory leaks in single-page applications, and providing a better user experience by handling loading states and potential failures.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs