← Back to all snippets
JAVASCRIPT

Fetching Data from a REST API with Loading and Error States

Learn to perform basic GET requests using JavaScript's Fetch API, including handling loading indicators and gracefully managing potential API errors for a better user experience.

async function fetchData(url) {
    let isLoading = true;
    let data = null;
    let error = 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;
    } finally {
        isLoading = false;
        // In a real app, you'd update your UI here, e.g., using React state or DOM manipulation
        console.log('Is Loading:', isLoading);
        console.log('Data:', data);
        console.log('Error:', error);
    }
    return { data, error, isLoading };
}

// Example Usage:
// fetchData('https://jsonplaceholder.typicode.com/posts/1').then(result => {
//     console.log('Result:', result);
// });
// fetchData('https://api.nonexistenturl.com/data').then(result => {
//     console.log('Result (error expected):', result);
// });
How it works: This snippet demonstrates how to fetch data from a REST API using the native Fetch API in JavaScript. It incorporates `async/await` for cleaner asynchronous code and includes crucial error handling with a `try...catch` block. Additionally, it shows how to manage a `isLoading` state, which is vital for providing user feedback during network requests, and handles both network errors and non-OK HTTP responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs