JAVASCRIPT

Robust Client-Side Data Fetching with Async/Await

Learn to fetch data from REST APIs using JavaScript's native Fetch API, incorporating async/await for cleaner code, error handling, and managing loading states in your web applications.

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

  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    data = await response.json();
  } catch (err) {
    error = err.message;
    console.error('Fetch error:', err);
  } finally {
    isLoading = false;
    // In a real application, you might update a UI state here
    console.log('Fetch completed. Loading:', isLoading, 'Error:', error, 'Data:', data);
  }
  return { data, error, isLoading };
}

// Example usage:
// fetchData('https://jsonplaceholder.typicode.com/posts/1').then(result => {
//   if (result.error) {
//     console.error('Failed to fetch:', result.error);
//   } else {
//     console.log('Fetched data:', result.data);
//   }
// });
How it works: This snippet demonstrates how to perform robust data fetching from an API using JavaScript's `async/await` syntax with the native `fetch` API. It includes crucial error handling with a `try...catch` block to gracefully manage network issues or non-2xx HTTP responses. A `finally` block ensures that loading states are properly reset, making it ideal for managing UI feedback like spinners or error messages during API calls.

Need help integrating this into your project?

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

Hire DigitalCodeLabs