By the end of this lesson, you will:
ℹ️ Info Building on Basics In the last lesson, you made API calls in the browser. Now we'll use JavaScript to fetch data and display it on webpages - just like real apps do!
JSON (JavaScript Object Notation) is like a universal language for data:
{
"student": {
"name": "Sarah",
"age": 15,
"grades": [95, 87, 92],
"isActive": true,
"mentor": null
}
}
Type | Example | Description |
---|---|---|
String | "Hello World" |
Text in quotes |
Number | 42 or 3.14 |
No quotes needed |
Boolean | true or false |
Yes/no values |
Null | null |
Empty/nothing |
Object | {"key": "value"} |
Group of data |
Array | [1, 2, 3] |
List of items |
const data = {
"user": {
"name": "Alex",
"hobbies": ["coding", "gaming"],
"address": {
"city": "New York"
}
}
};
// Access nested data
console.log(data.user.name); // "Alex"
console.log(data.user.hobbies[0]); // "coding"
console.log(data.user.address.city); // "New York"
// Simple fetch
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Async/await makes code cleaner and easier to read:
// Using async/await (cleaner!)
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
💡 Why Async/Await?
- Easier to read (looks like normal code)
- Better error handling with try/catch
- No "callback hell" with .then chains
Here's the complete flow:
// 1. Get the data
async function displayWeather() {
// 2. Fetch from API
const response = await fetch('https://api.weather.com/current');
const weather = await response.json();
// 3. Update HTML
document.getElementById('temp').innerText = weather.temperature;
document.getElementById('city').innerText = weather.location;
document.getElementById('condition').innerText = weather.description;
}
async function showUserList() {
const response = await fetch('https://api.example.com/users');
const users = await response.json();
// Build HTML for each user
let html = '';
users.forEach(user => {
html += `
<div class="user-card">
<h3>${user.name}</h3>
<p>Email: ${user.email}</p>
<p>City: ${user.city}</p>
</div>
`;
});
// Insert into page
document.getElementById('users').innerHTML = html;
}
async function fetchData() {
const response = await fetch('https://api.example.com/data');
// Check if request was successful
if (response.ok) {
const data = await response.json();
console.log('Success:', data);
} else {
console.error('HTTP Error:', response.status);
}
}
const response = await fetch('https://api.example.com/data');
console.log(response.status); // 200, 404, 500, etc.
console.log(response.ok); // true if status 200-299
console.log(response.statusText); // "OK", "Not Found", etc.
console.log(response.url); // The final URL after redirects
async function safeAPICall() {
const loadingDiv = document.getElementById('loading');
const errorDiv = document.getElementById('error');
const resultDiv = document.getElementById('result');
// Show loading state
loadingDiv.style.display = 'block';
errorDiv.style.display = 'none';
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
// Display success
resultDiv.innerHTML = `<p>Success! Got ${data.length} items</p>`;
} catch (error) {
// Display error
errorDiv.style.display = 'block';
errorDiv.innerHTML = `<p>Error: ${error.message}</p>`;
} finally {
// Hide loading
loadingDiv.style.display = 'none';
}
}
async function displayProducts() {
const response = await fetch('https://api.store.com/products');
const products = await response.json();
// Method 1: forEach
products.forEach(product => {
console.log(`${product.name}: ${product.price}`);
});
// Method 2: map (creates new array)
const names = products.map(product => product.name);
console.log('All products:', names);
// Method 3: filter (finds matching items)
const cheap = products.filter(product => product.price < 10);
console.log('Affordable products:', cheap);
}
async function createWeatherDashboard(city) {
const apiKey = 'your-api-key'; // We'll learn about this next lesson!
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}`;
try {
const response = await fetch(url);
const data = await response.json();
// Extract what we need
const temp = Math.round(data.main.temp);
const description = data.weather[0].description;
const humidity = data.main.humidity;
// Update the dashboard
document.getElementById('dashboard').innerHTML = `
<div class="weather-widget">
<h2>${city}</h2>
<div class="temp">${temp}°C</div>
<p>${description}</p>
<p>Humidity: ${humidity}%</p>
</div>
`;
} catch (error) {
document.getElementById('dashboard').innerHTML =
`<p>Could not load weather for ${city}</p>`;
}
}
// Use it
createWeatherDashboard('London');
async function loadWithStates() {
// Set loading state
setUIState('loading');
try {
const data = await fetchData();
setUIState('success', data);
} catch (error) {
setUIState('error', error);
}
}
function setUIState(state, data = null) {
const container = document.getElementById('container');
switch(state) {
case 'loading':
container.innerHTML = '<div class="spinner">Loading...</div>';
break;
case 'success':
container.innerHTML = `<div class="data">${data}</div>`;
break;
case 'error':
container.innerHTML = '<div class="error">Something went wrong</div>';
break;
}
}
Given this API response, extract the email:
const response = {
"data": {
"user": {
"contact": {
"email": "user@example.com"
}
}
}
};
// Your code here
Make this code safe if properties don't exist:
// This might crash if data is missing!
const city = data.user.address.city;
// Make it safe:
const city = data?.user?.address?.city || 'Unknown';
You've learned to:
These skills are the foundation of modern web development!
In Concept 03, you'll learn about: