DeveloperBreeze

JavaScript Code Snippet: Fetch and Display Data from an API

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch API Example</title>
</head>
<body>
    <h1>User Information</h1>
    <ul id="user-list"></ul>

    <script>
        async function fetchUserData() {
            try {
                const response = await fetch('https://jsonplaceholder.typicode.com/users');
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const users = await response.json();
                displayUsers(users);
            } catch (error) {
                console.error('Fetch error:', error);
            }
        }

        function displayUsers(users) {
            const userList = document.getElementById('user-list');
            users.forEach(user => {
                const listItem = document.createElement('li');
                listItem.textContent = `${user.name} - ${user.email}`;
                userList.appendChild(listItem);
            });
        }

        fetchUserData();
    </script>
</body>
</html>

Continue Reading

Handpicked posts just for you — based on your current read.

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!