In this lesson, you will learn how to handle missing or invalid saved data in your task planner using JavaScript. This skill is vital for keeping your application running smoothly and avoiding crashes caused by unexpected data.
When you save data in the browser, it may sometimes be missing or not in the correct format. For example, if a user sets a task without a title, our app must handle this situation. Otherwise, it can lead to errors and a bad user experience. Thus, managing these cases is essential for developers.
File: handle_data.js
// Function to get task data from localStorage
function getTask() {
let task = localStorage.getItem('task');
// Check if task is valid
if (!task) {
return 'No task found.';
}
try {
task = JSON.parse(task);
} catch (error) {
return 'Invalid task data.';
}
return task.title || 'Task has no title.';
}
// Save a valid task
localStorage.setItem('task', JSON.stringify({ title: 'Study JavaScript' }));
// Save an invalid task
localStorage.setItem('task', JSON.stringify({}));
console.log(getTask()); // Output depends on whether valid or invalid task is accessed
No task found.
Invalid task data.
Task has no title.
This code creates a function getTask that retrieves a task from localStorage. It first checks for the existence of the task; if the data is invalid, it catches the error and returns a message. The use of JSON.parse converts the string back into an object. By properly managing exceptions, you avoid issues before they affect your application.
For your project, create a function that saves a task. This function must ensure that a task always has a title and should notify the user if it does not. Effective communication with users is crucial, so they understand what is needed. This will enhance the user interface of your task planner.
function saveTask(title) {
if (!title) {
console.log('Task title cannot be empty.');
return;
}
const task = { title: title };
localStorage.setItem('task', JSON.stringify(task));
console.log('Task saved:', task);
}
// Test the function
saveTask(); // Output: Task title cannot be empty.
saveTask('Learn JavaScript'); // Output: Task saved: { title: 'Learn JavaScript' }
JSON.stringify and JSON.parse.try-catch for exception handling when parsing data.For more details on JavaScript basics, check out the What Is JavaScript? Examples from Everyday Websites lesson.