← Back to all snippets
JAVASCRIPT

Robust Data Fetching from an API with Loading and Error States

Learn to fetch data from a REST API using async/await with robust error handling, loading state management, and clear UI feedback. This snippet ensures a smooth user experience.

async function fetchDataWithStates(url) {
  let data = null;
  let loading = true;
  let error = null;

  try {
    const response = await fetch(url);
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || `HTTP error! Status: ${response.status}`);
    }
    data = await response.json();
  } catch (err) {
    error = err.message;
  } finally {
    loading = false;
  }

  return { data, loading, error };
}

// Example Usage (in a React/Vue component or plain JS context)
// const { data, loading, error } = await fetchDataWithStates('https://api.example.com/items');
// if (loading) console.log('Loading...');
// if (error) console.error('Error:', error);
// if (data) console.log('Data:', data);
How it works: This snippet demonstrates how to perform a `GET` request using the `fetch` API with modern `async/await` syntax. It incorporates crucial error handling with `try/catch` and checks `response.ok` for HTTP status codes, providing a structured way to manage loading, data, and error states often required in UI development.

Need help integrating this into your project?

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

Hire DigitalCodeLabs