In this lesson, you will learn how to load course data and handle errors in your JavaScript project. This skill is essential for creating a smooth user experience.
By the end of this lesson, you will be able to load course data from an API and manage errors effectively.
Imagine you are checking the weather on a website. If the website cannot find the weather data, it shows an error message instead of crashing. This lesson helps you do the same with your student learning dashboard.
File: load-course-data.js
const loadCourseData = async () => {
try {
const response = await fetch('https://api.example.com/courses');
if (!response.ok) {
throw new Error('Network response was not ok' + response.statusText);
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error loading course data:', error);
alert('Could not load course data. Please try again later.');
}
};
loadCourseData();
Expected Output:
[ { title: 'JavaScript Basics', id: 1 }, { title: 'Advanced JavaScript', id: 2 } ]
const response = await fetch('https://api.example.com/courses'); – This line fetches course data from a URL.if (!response.ok) – This checks if the response is valid.console.error('Error loading course data:', error); – This prints the error to the console.Now, modify the code to display the course titles in a list on your webpage.
const loadCourseData = async () => {
try {
const response = await fetch('https://api.example.com/courses');
if (!response.ok) {
throw new Error('Network response was not ok' + response.statusText);
}
const data = await response.json();
const courseList = document.getElementById('course-list');
data.forEach(course => {
const listItem = document.createElement('li');
listItem.textContent = course.title;
courseList.appendChild(listItem);
});
} catch (error) {
console.error('Error loading course data:', error);
alert('Could not load course data. Please try again later.');
}
};
loadCourseData();